package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.ResChangeSchoolReturn;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.enums.StatusStudentGradeEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.ChangeSchoolMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 转校 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-04-06
 */
@Service
public class ChangeSchoolServiceImpl extends ServiceImpl<ChangeSchoolMapper, ChangeSchool> implements IChangeSchoolService {

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    IChangeSchoolContentService iChangeSchoolContentService;

    @Autowired
    @Lazy
    IChangeSchoolDetailService iChangeSchoolDetailService;

    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IOrderTransferService iOrderTransferService;

    @Autowired
    @Lazy
    IOrderTransferDetailService iOrderTransferDetailService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    IRecordCostService iRecordCostService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IRepairCourseService iRepairCourseService;

    @Autowired
    @Lazy
    ICourseSchedulingService iCourseSchedulingService;

    @Autowired
    @Lazy
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    @Lazy
    IDealInfoService iDealInfoService;

    @Autowired
    @Lazy
    IOrderPayAccountService iOrderPayAccountService;

    @Autowired
    @Lazy
    IOrderDisDetailService iOrderDisDetailService;

    @Autowired
    @Lazy
    IOrderDisClanService iOrderDisClanService;

    @Autowired
    @Lazy
    IOrderDisPriceService iOrderDisPriceService;

    @Autowired
    @Lazy
    IStudentSchoolService iStudentSchoolService;

    @Autowired
    @Lazy
    RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    @Lazy
    IRecordCourseLackService iRecordCourseLackService;

    @Autowired
    @Lazy
    IStudentSignInService iStudentSignInService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    // 模拟目录结构，键名以某个前缀开始
    private static final String DIRECTORY_PREFIX = "changeSchool:";

    @Override
    @Transactional
    public boolean changeSchoolAction(ChangeSchoolDetail changeSchoolDetail) throws ParseException {
        boolean rs = false;
        //1按学员，2按教师，3按校长
        if (changeSchoolDetail.getType().equals(1)) {
            rs = this.changeSchoolForStudent(changeSchoolDetail);
            if (rs) {
                redisTemplate.delete(DIRECTORY_PREFIX + changeSchoolDetail.getOutSchoolId() + ":" + changeSchoolDetail.getSubjectsId() + ":" + changeSchoolDetail.getStudentId());
            }
        } else if (changeSchoolDetail.getType().equals(2)) {
            rs = this.changeSchoolForTeacher(changeSchoolDetail);
        } else if (changeSchoolDetail.getType().equals(3)) {
            rs = this.changeSchoolForTeacher(changeSchoolDetail);
        }
        return rs;
    }

    /**
     * 学生类型转校
     *
     * @param changeSchoolDetailParam
     * @return
     */
    public boolean changeSchoolForStudent(ChangeSchoolDetail changeSchoolDetailParam) {
        ChangeSchoolDetail changeSchoolDetail = iChangeSchoolDetailService.getById(changeSchoolDetailParam.getId());
        if (!changeSchoolDetail.getStatus().equals(0)) {
            return false;//已转校
        }
        Object obj = redisTemplate.opsForValue().get(DIRECTORY_PREFIX + changeSchoolDetailParam.getOutSchoolId() + ":" + changeSchoolDetailParam.getSubjectsId() + ":" + changeSchoolDetailParam.getStudentId());
        if (obj != null) {
            changeSchoolDetail.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
            changeSchoolDetail.setRemark("有相同的转校数据，提交重复了，如还未转校");
            iChangeSchoolDetailService.updateById(changeSchoolDetail);
            return false;
        }
        redisTemplate.opsForValue().set(DIRECTORY_PREFIX + changeSchoolDetailParam.getOutSchoolId() + "-" + changeSchoolDetailParam.getSubjectsId() + "-" + changeSchoolDetailParam.getStudentId(), changeSchoolDetailParam, 5, TimeUnit.MINUTES);


        Integer lessonType = 1;

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("year_part", changeSchoolDetailParam.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", changeSchoolDetailParam.getQuarterNum());
        orderDetailQueryWrapper.eq("school_id", changeSchoolDetailParam.getOutSchoolId());
        orderDetailQueryWrapper.eq("subjects_id", changeSchoolDetailParam.getSubjectsId());
        orderDetailQueryWrapper.eq("student_id", changeSchoolDetailParam.getStudentId());
        orderDetailQueryWrapper.eq("lesson_type", lessonType);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.gt("residue_course_count", 0);

        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);

        /*BigDecimal residuePriceAll = new BigDecimal(0);//剩余金额
        Integer residueCourseCountAll = 0;//剩余课次
        for (OrderDetail orderDetail : orderDetailList) {
            residuePriceAll = residuePriceAll.add(orderDetail.getResiduePrice());
            residueCourseCountAll += orderDetail.getResidueCourseCount();
        }*/
        //changeSchoolDetailParam.setTurnOutHouse(residueCourseCountAll);
        //changeSchoolDetailParam.setTurnOutPrice(residuePriceAll);

        //剩余转校
        Result result = this.returnOremiumForResidue(changeSchoolDetailParam, orderDetailList);
        if (result.getCode().equals(Code.OK)) {
            ResChangeSchoolReturn resChangeSchoolReurn = (ResChangeSchoolReturn) result.getData();
            //报名
            Result resultApply = this.changeApply(changeSchoolDetailParam, resChangeSchoolReurn.getOrderApply(), resChangeSchoolReurn.getCourse(), resChangeSchoolReurn.getCoursePricing(), resChangeSchoolReurn.getOrderDetail(),1);
            if (resultApply.getCode().equals(Code.OK)) {
                changeSchoolDetail.setStatus(1);//0未转校，1已转校，2转校失败（操作转校时才使用）
                changeSchoolDetail.setTurnOutHouse(resChangeSchoolReurn.getResidueCourseCountAll());
                changeSchoolDetail.setTurnOutPrice(resChangeSchoolReurn.getResiduePriceAll());
            } else {
                changeSchoolDetail.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
                changeSchoolDetail.setRemark(result.getMessage());
            }
        } else {
            changeSchoolDetail.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
            changeSchoolDetail.setRemark(result.getMessage());
        }
        iChangeSchoolDetailService.updateById(changeSchoolDetail);
        return true;
    }

    /**
     * 教师类型转校
     *
     * @param changeSchoolDetailParam
     * @return
     */
    public boolean changeSchoolForTeacher(ChangeSchoolDetail changeSchoolDetailParam) throws ParseException {
        ChangeSchoolDetail changeSchoolDetail = iChangeSchoolDetailService.getOneInfo(changeSchoolDetailParam.getId());
        if (changeSchoolDetail == null) {
            return false;
        }
        ChangeSchool changeSchool = changeSchoolDetail.getChangeSchool();
        if (changeSchool == null) {
            return false;
        }
        if (changeSchool.getChangeType().equals(0)){
            //剩余转出
            this.changeSchoolForTeacherResidue(changeSchoolDetailParam,changeSchoolDetail);
        }else if (changeSchool.getChangeType().equals(1)){
            //全部转出
            this.changeSchoolForTeacherAll(changeSchoolDetailParam,changeSchoolDetail);
        }else {
            return false;
        }
        return true;
    }

    /**
     * 按老师全部转出
     * @param changeSchoolDetailParam
     * @param changeSchoolDetail
     * @return
     */
    public boolean changeSchoolForTeacherAll(ChangeSchoolDetail changeSchoolDetailParam,ChangeSchoolDetail changeSchoolDetail) throws ParseException {

        if (!changeSchoolDetail.getStatus().equals(0)) {
            return false;//已转校
        }

        Integer lessonType = 1;
        //获取转出校区学生转校前的课时与金额
        OrderDetail orderDetailCourseAndPrice = iOrderDetailService.getCourseHouseAndPrice(changeSchoolDetailParam.getYearPart(), changeSchoolDetailParam.getQuarterNum(), changeSchoolDetailParam.getOutSchoolId(), changeSchoolDetailParam.getSubjectsId(), lessonType, changeSchoolDetailParam.getStudentId());

        Object obj = redisTemplate.opsForValue().get(DIRECTORY_PREFIX + changeSchoolDetailParam.getOutSchoolId() + ":" + changeSchoolDetailParam.getSubjectsId() + ":" + changeSchoolDetailParam.getStudentId());
        if (obj != null) {
            changeSchoolDetail.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
            changeSchoolDetail.setRemark("有相同的转校数据，提交重复了，如还未转校请稍候重新提交");
            iChangeSchoolDetailService.updateById(changeSchoolDetail);
            return false;
        }
        redisTemplate.opsForValue().set(DIRECTORY_PREFIX + changeSchoolDetailParam.getOutSchoolId() + "-" + changeSchoolDetailParam.getSubjectsId() + "-" + changeSchoolDetailParam.getStudentId(), changeSchoolDetailParam, 5, TimeUnit.MINUTES);

        ChangeSchool changeSchool = changeSchoolDetail.getChangeSchool();
        Integer changeType = changeSchool.getChangeType();//0部分转出，1全部转出（包含已使用的课时）

        /**
         * 全部转出
         */
        Result result = this.returnAndApply(changeSchoolDetailParam);
        if (result.getCode().equals(Code.OK)) {
            //this.updateChangeSchoolDataAll(changeSchoolDetailParam);

            //移动智能课与刷题班
            //this.mvOtherCourseDataForTeacher(changeSchoolDetailParam);
            //this.mvOtherCourseData(changeSchoolDetailParam);
            return true;
        }else {
            return false;
        }

        /*changeSchoolDetail.setStatus(1);//0未转校，1已转校，2转校失败（操作转校时才使用）
        changeSchoolDetail.setTurnOutHouse(orderDetailCourseAndPrice.getAllCourseCount());
        changeSchoolDetail.setTurnOutPrice(orderDetailCourseAndPrice.getPrice());
        changeSchoolDetail.setAllCourseCount(orderDetailCourseAndPrice.getAllCourseCount());
        changeSchoolDetail.setAllPrice(orderDetailCourseAndPrice.getPrice());
        changeSchoolDetail.setUseCourseCount(orderDetailCourseAndPrice.getUseCourseCount());
        changeSchoolDetail.setUsePrice(orderDetailCourseAndPrice.getUsePrice());
        iChangeSchoolDetailService.updateById(changeSchoolDetail);*/

    }


    /**
     * 按老师剩余转出
     * @param changeSchoolDetailParam
     * @param changeSchoolDetail
     * @return
     */
    public boolean changeSchoolForTeacherResidue(ChangeSchoolDetail changeSchoolDetailParam,ChangeSchoolDetail changeSchoolDetail) throws ParseException {
        if (!changeSchoolDetail.getStatus().equals(0)) {
            return false;//已转校
        }
        Object obj = redisTemplate.opsForValue().get(DIRECTORY_PREFIX + changeSchoolDetailParam.getOutSchoolId() + ":" + changeSchoolDetailParam.getSubjectsId() + ":" + changeSchoolDetailParam.getStudentId());
        if (obj != null) {
            changeSchoolDetail.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
            changeSchoolDetail.setRemark("有相同的转校数据，提交重复了，如还未转校");
            iChangeSchoolDetailService.updateById(changeSchoolDetail);
            return false;
        }
        redisTemplate.opsForValue().set(DIRECTORY_PREFIX + changeSchoolDetailParam.getOutSchoolId() + "-" + changeSchoolDetailParam.getSubjectsId() + "-" + changeSchoolDetailParam.getStudentId(), changeSchoolDetailParam, 5, TimeUnit.MINUTES);


        Integer lessonType = 1;

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("year_part", changeSchoolDetailParam.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", changeSchoolDetailParam.getQuarterNum());
        orderDetailQueryWrapper.eq("school_id", changeSchoolDetailParam.getOutSchoolId());
        orderDetailQueryWrapper.eq("subjects_id", changeSchoolDetailParam.getSubjectsId());
        orderDetailQueryWrapper.eq("student_id", changeSchoolDetailParam.getStudentId());
        orderDetailQueryWrapper.eq("lesson_type", lessonType);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.gt("residue_course_count", 0);

        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);

        Result result = this.returnOremiumForResidue(changeSchoolDetailParam, orderDetailList);
        if (result.getCode().equals(Code.OK)) {
            ResChangeSchoolReturn resChangeSchoolReurn = (ResChangeSchoolReturn) result.getData();
            Result resultApply = this.changeApply(changeSchoolDetailParam, resChangeSchoolReurn.getOrderApply(), resChangeSchoolReurn.getCourse(), resChangeSchoolReurn.getCoursePricing(), resChangeSchoolReurn.getOrderDetail(),1);
            if (resultApply.getCode().equals(Code.OK)) {
                changeSchoolDetail.setStatus(1);//0未转校，1已转校，2转校失败（操作转校时才使用）
                changeSchoolDetail.setTurnOutHouse(resChangeSchoolReurn.getResidueCourseCountAll());
                changeSchoolDetail.setTurnOutPrice(resChangeSchoolReurn.getResiduePriceAll());
                ResChangeSchoolReturn resApplyReturn = (ResChangeSchoolReturn) resultApply.getData();
                //报名完成添加其它数据
                this.updateChangeSchoolDataForResidue(changeSchoolDetailParam,resApplyReturn.getOrderDetail(),1);
            } else {
                changeSchoolDetail.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
                changeSchoolDetail.setRemark(result.getMessage());
            }
        } else {
            changeSchoolDetail.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
            changeSchoolDetail.setRemark(result.getMessage());
        }
        iChangeSchoolDetailService.updateById(changeSchoolDetail);
        return true;
    }



    /**
     * 退费
     *
     * @return
     */
    public boolean returnOremium(ChangeSchoolDetail changeSchoolDetailParam, List<OrderDetail> orderDetailList) {

        Long orderNo = idWorker.nextId();

        LocalDate nowDate = LocalDate.now();
        OrderApply returnOrderApply = new OrderApply();//退费
        OrderTransfer orderTransfer = new OrderTransfer();
        orderTransfer.setId(idWorker.nextId());
        Organization outSchool = iOrganizationService.getById(changeSchoolDetailParam.getOutSchoolId());
        Staff staff = new Staff();
        if (changeSchoolDetailParam.getCreatedId() == null || changeSchoolDetailParam.getCreatedId().equals(1568138350324350975L)) {
            staff.setId(changeSchoolDetailParam.getCreatedId());
            staff.setName("超级管理员");
        } else {
            staff = iStaffService.getById(changeSchoolDetailParam.getCreatedId());
        }

        returnOrderApply.setId(idWorker.nextId());
        returnOrderApply.setOrderNo(orderNo.toString());
        Integer receiptNo = CommonUtil.getReceiptNo(7);
        returnOrderApply.setReceiptNo(receiptNo.toString());
        returnOrderApply.setChangeSchoolDetailId(changeSchoolDetailParam.getId());//转校详情id
        returnOrderApply.setLessonType(1);
        returnOrderApply.setCostType(2);//1收入，2支出
        returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
        returnOrderApply.setStudentId(changeSchoolDetailParam.getStudentId());
        returnOrderApply.setYearPart(changeSchoolDetailParam.getYearPart());
        returnOrderApply.setQuarterNum(changeSchoolDetailParam.getQuarterNum());
        //returnOrderApply.setHandleSchoolId(changeSchoolDetailParam.getInSchoolId());
        returnOrderApply.setHandleSchoolName(outSchool.getName());
        returnOrderApply.setSchoolId(changeSchoolDetailParam.getOutSchoolId());//所属校区
        returnOrderApply.setHandleSchoolId(changeSchoolDetailParam.getOutSchoolId());
        returnOrderApply.setHandlePersonId(changeSchoolDetailParam.getCreatedId());
        returnOrderApply.setHandlePersonName(staff.getName());
        returnOrderApply.setHandlePersonName(staff.getName());
        returnOrderApply.setHandleDate(nowDate);
        returnOrderApply.setCreatedId(changeSchoolDetailParam.getCreatedId());
        returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
        returnOrderApply.setSignType(3);

        List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
        Long outCourseId = null;
        if (orderDetailList.size() == 0) {
            //return new Result(Code.ERROR, "", "剩余课时为0，不能转校");
            throw  new CommonException(ResultCode.COURSE_ZERO);
        }

        BigDecimal residuePriceAll = new BigDecimal(0);//剩余金额
        Integer residueCourseCountAll = 0;//剩余课次

        BigDecimal userPriceAll = new BigDecimal(0);
        Integer userCourseCountAll = 0;

        for (OrderDetail orderDetailOld : orderDetailList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(orderDetailOld, orderDetail);

            outCourseId = orderDetail.getCourseId();
            //residuePriceAll = residuePriceAll.add(orderDetail.getResiduePrice());
            //residueCourseCountAll += orderDetail.getResidueCourseCount();

            userPriceAll = userPriceAll.add(orderDetail.getUsePrice());
            userCourseCountAll += orderDetail.getUseCourseCount();

            BigDecimal turnOutPriceNow = orderDetail.getResiduePrice().add(orderDetail.getUsePrice());
            Integer turnOutCourseCountNow = orderDetail.getResidueCourseCount() + orderDetail.getUseCourseCount();

            residuePriceAll = residuePriceAll.add(turnOutPriceNow);//使用加剩余金额
            residueCourseCountAll += turnOutCourseCountNow;//使用加剩余课时

            OrderTransferDetail orderTransferDetail = new OrderTransferDetail();
            orderTransferDetail.setOldOrderDetailId(orderDetail.getId());
            orderTransferDetail.setOldOrderId(orderDetail.getOrderId());
            orderTransferDetail.setOrderId(returnOrderApply.getId());
            orderTransferDetail.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
            orderTransferDetail.setOutHouse(orderDetail.getResidueCourseCount());
            orderTransferDetail.setOutPrice(orderDetail.getResiduePrice());
            orderTransferDetailList.add(orderTransferDetail);

            //转出课时
            BigDecimal turnOutPrice = orderDetail.getTurnOutPrice().add(turnOutPriceNow);
            orderDetail.setTurnOutPrice(turnOutPrice);
            //转出金额
            Integer turnOutHouse = orderDetail.getTurnOutHouse() + turnOutCourseCountNow;
            orderDetail.setTurnOutHouse(turnOutHouse);


            Integer turnOutUseHouse = 0;//累计转出使用课时
            BigDecimal turnOutUsePrice = new BigDecimal(0);//累计转出使用金额
            turnOutUseHouse += orderDetail.getUseCourseCount();
            turnOutUsePrice = turnOutUsePrice.add(orderDetail.getUsePrice());

            orderDetail.setResiduePrice(new BigDecimal(0));
            orderDetail.setResidueCourseCount(0);
            orderDetail.setUsePrice(new BigDecimal(0));
            orderDetail.setUseCourseCount(0);
            orderDetail.setTurnOutUseHouse(turnOutUseHouse);
            orderDetail.setTurnOutUsePrice(turnOutUsePrice);
            iOrderDetailService.updateById(orderDetail);

        }
        orderTransfer.setOrderId(returnOrderApply.getId());
        orderTransfer.setOutSchoolId(changeSchoolDetailParam.getOutSchoolId());
        orderTransfer.setInSchoolId(changeSchoolDetailParam.getInSchoolId());
        orderTransfer.setOutGradeId(outCourseId);//转出课程id
        orderTransfer.setInGradeId(outCourseId);//转入课程id
        orderTransfer.setOutPrice(residuePriceAll);
        orderTransfer.setOutHouse(residueCourseCountAll / 3);//这里是课次，所以除3
        orderTransfer.setOutType(1);
        orderTransfer.setCreatedId(changeSchoolDetailParam.getCreatedId());
        orderTransfer.setOrderType(4);

        Course outCourse = iCourseService.getById(orderTransfer.getOutGradeId());
        if (outCourse == null) {
            //System.out.println("课程为空");
            //return new Result(Code.ERROR, "", "转出校区课程为空");
            throw  new CommonException(ResultCode.OUT_COURSE_NOT);
        }
        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        tradeContent += "转校退费：" + outCourse.getName() + "退" + orderTransfer.getOutHouse() + "课次，应退学费" + orderTransfer.getOutPrice() + "元";

        returnOrderApply.setTradeContent(tradeContent);
        returnOrderApply.setPrice(orderTransfer.getOutPrice());//设置退费金额
        returnOrderApply.setSolidPrice(orderTransfer.getOutPrice());//实收金额
        changeSchoolDetailParam.setTurnOutHouse(residueCourseCountAll);
        changeSchoolDetailParam.setTurnOutPrice(residuePriceAll);

        CoursePricing coursePricing = this.getCoursePricing(outCourse, changeSchoolDetailParam.getTurnOutHouse(), changeSchoolDetailParam.getInSchoolId());
        if (coursePricing == null) {
            //return new Result(Code.ERROR, "", "转入校区课程价格为空");
            throw  new CommonException(ResultCode.COURSE_PRICE_NOT);
        }

        iOrderTransferService.save(orderTransfer);
        iOrderTransferDetailService.saveBatch(orderTransferDetailList);
        iOrderApplyService.save(returnOrderApply);
        //this.changeApply(changeSchoolDetailParam, returnOrderApply, outCourse, coursePricing);

        //报名使用
        OrderDetail orderDetailOut = new OrderDetail();
        orderDetailOut.setUsePrice(userPriceAll);//使用金额
        orderDetailOut.setUseCourseCount(userCourseCountAll);//使用课时
        orderDetailOut.setOutPrice(residuePriceAll);//转出金额（包含了使用金额）
        orderDetailOut.setOutHouse(residueCourseCountAll);//转出课时(包含了使用课时)

        ResChangeSchoolReturn resChangeSchoolReurn = new ResChangeSchoolReturn();
        resChangeSchoolReurn.setOrderApply(returnOrderApply);
        resChangeSchoolReurn.setOrderDetail(orderDetailOut);
        resChangeSchoolReurn.setCourse(outCourse);
        resChangeSchoolReurn.setCoursePricing(coursePricing);
        resChangeSchoolReurn.setResiduePriceAll(residuePriceAll);
        resChangeSchoolReurn.setResidueCourseCountAll(residueCourseCountAll);
        //return new Result(Code.OK, resChangeSchoolReurn, "成功");
        return true;
    }

    /**
     * 退费(只退剩余课时)
     * @param changeSchoolDetailParam
     * @param orderDetailList
     * @return
     */
    public Result returnOremiumForResidue(ChangeSchoolDetail changeSchoolDetailParam, List<OrderDetail> orderDetailList) {

        Long orderNo = idWorker.nextId();

        LocalDate nowDate = LocalDate.now();
        OrderApply returnOrderApply = new OrderApply();//退费
        OrderTransfer orderTransfer = new OrderTransfer();
        orderTransfer.setId(idWorker.nextId());
        Organization outSchool = iOrganizationService.getById(changeSchoolDetailParam.getOutSchoolId());
        Staff staff = new Staff();
        if (changeSchoolDetailParam.getCreatedId() == null || changeSchoolDetailParam.getCreatedId().equals(1568138350324350975L)) {
            staff.setId(changeSchoolDetailParam.getCreatedId());
            staff.setName("超级管理员");
        } else {
            staff = iStaffService.getById(changeSchoolDetailParam.getCreatedId());
        }

        returnOrderApply.setId(idWorker.nextId());
        returnOrderApply.setOrderNo(orderNo.toString());
        Integer receiptNo = CommonUtil.getReceiptNo(7);
        returnOrderApply.setReceiptNo(receiptNo.toString());
        returnOrderApply.setChangeSchoolDetailId(changeSchoolDetailParam.getId());//转校详情id
        returnOrderApply.setLessonType(1);
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);//退费和转校两个都设置为一样的状态
        returnOrderApply.setCostType(2);//1收入，2支出
        returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
        returnOrderApply.setStudentId(changeSchoolDetailParam.getStudentId());
        returnOrderApply.setYearPart(changeSchoolDetailParam.getYearPart());
        returnOrderApply.setQuarterNum(changeSchoolDetailParam.getQuarterNum());
        //returnOrderApply.setHandleSchoolId(changeSchoolDetailParam.getInSchoolId());
        returnOrderApply.setHandleSchoolName(outSchool.getName());
        returnOrderApply.setSchoolId(changeSchoolDetailParam.getOutSchoolId());//所属校区
        returnOrderApply.setHandleSchoolId(changeSchoolDetailParam.getOutSchoolId());
        returnOrderApply.setHandlePersonId(changeSchoolDetailParam.getCreatedId());
        returnOrderApply.setHandlePersonName(staff.getName());
        returnOrderApply.setHandlePersonName(staff.getName());
        returnOrderApply.setHandleDate(nowDate);
        returnOrderApply.setCreatedId(changeSchoolDetailParam.getCreatedId());
        returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
        returnOrderApply.setSignType(3);

        List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
        Long outCourseId = null;
        if (orderDetailList.size() == 0) {
            return new Result(Code.ERROR, "", "剩余课时为0，不能转校");
            //throw  new CommonException(ResultCode.COURSE_ZERO);
        }

        BigDecimal residuePriceAll = new BigDecimal(0);//剩余金额
        Integer residueCourseCountAll = 0;//剩余课次

        BigDecimal userPriceAll = new BigDecimal(0);
        Integer userCourseCountAll = 0;
        for (OrderDetail orderDetailOld : orderDetailList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(orderDetailOld, orderDetail);
            outCourseId = orderDetail.getCourseId();
            Integer turnOutCourseCountNow = orderDetail.getResidueCourseCount();
            residueCourseCountAll += turnOutCourseCountNow;//使用加剩余课时
        }

        changeSchoolDetailParam.setTurnOutHouse(residueCourseCountAll);

        Course outCourse = iCourseService.getById(outCourseId);
        if (outCourse == null) {
            //System.out.println("课程为空");
            return new Result(Code.ERROR, "", "转出校区课程为空");
        }

        CoursePricing coursePricing = this.getCoursePricing(outCourse, changeSchoolDetailParam.getTurnOutHouse(), changeSchoolDetailParam.getInSchoolId());
        if (coursePricing == null) {
            return new Result(Code.ERROR, "", "转入校区课程价格为空");
            //throw  new CommonException(ResultCode.COURSE_PRICE_NOT);
        }


        residueCourseCountAll = 0;//剩余课次
        for (OrderDetail orderDetailOld : orderDetailList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(orderDetailOld, orderDetail);

            outCourseId = orderDetail.getCourseId();
            //residuePriceAll = residuePriceAll.add(orderDetail.getResiduePrice());
            //residueCourseCountAll += orderDetail.getResidueCourseCount();

            userPriceAll = userPriceAll.add(orderDetail.getUsePrice());
            userCourseCountAll += orderDetail.getUseCourseCount();

            BigDecimal turnOutPriceNow = orderDetail.getResiduePrice();
            Integer turnOutCourseCountNow = orderDetail.getResidueCourseCount();

            residuePriceAll = residuePriceAll.add(turnOutPriceNow);//使用加剩余金额
            residueCourseCountAll += turnOutCourseCountNow;//使用加剩余课时

            OrderTransferDetail orderTransferDetail = new OrderTransferDetail();
            orderTransferDetail.setOldOrderDetailId(orderDetail.getId());
            orderTransferDetail.setOldOrderId(orderDetail.getOrderId());
            orderTransferDetail.setOrderId(returnOrderApply.getId());
            orderTransferDetail.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
            orderTransferDetail.setOutHouse(orderDetail.getResidueCourseCount());
            orderTransferDetail.setOutPrice(orderDetail.getResiduePrice());
            orderTransferDetailList.add(orderTransferDetail);

            //转出课时
            BigDecimal turnOutPrice = orderDetail.getTurnOutPrice().add(turnOutPriceNow);
            orderDetail.setTurnOutPrice(turnOutPrice);
            //转出金额
            Integer turnOutHouse = orderDetail.getTurnOutHouse() + turnOutCourseCountNow;
            orderDetail.setTurnOutHouse(turnOutHouse);
            orderDetail.setResiduePrice(new BigDecimal(0));
            orderDetail.setResidueCourseCount(0);
            iOrderDetailService.updateById(orderDetail);

        }
        orderTransfer.setOrderId(returnOrderApply.getId());
        orderTransfer.setOutSchoolId(changeSchoolDetailParam.getOutSchoolId());
        orderTransfer.setInSchoolId(changeSchoolDetailParam.getInSchoolId());
        orderTransfer.setOutGradeId(outCourseId);//转出课程id
        orderTransfer.setInGradeId(outCourseId);//转入课程id
        orderTransfer.setOutPrice(residuePriceAll);
        orderTransfer.setOutHouse(residueCourseCountAll / 3);//这里是课次，所以除3
        orderTransfer.setOutType(1);
        orderTransfer.setCreatedId(changeSchoolDetailParam.getCreatedId());
        orderTransfer.setOrderType(4);

        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        tradeContent += "转校退费：" + outCourse.getName() + "退" + orderTransfer.getOutHouse() + "课次，应退学费" + orderTransfer.getOutPrice() + "元";

        returnOrderApply.setTradeContent(tradeContent);
        returnOrderApply.setPrice(orderTransfer.getOutPrice());//设置退费金额
        returnOrderApply.setSolidPrice(orderTransfer.getOutPrice());//实收金额
        changeSchoolDetailParam.setTurnOutHouse(residueCourseCountAll);
        changeSchoolDetailParam.setTurnOutPrice(residuePriceAll);



        iOrderTransferService.save(orderTransfer);
        iOrderTransferDetailService.saveBatch(orderTransferDetailList);
        iOrderApplyService.save(returnOrderApply);
        //this.changeApply(changeSchoolDetailParam, returnOrderApply, outCourse, coursePricing);

        //报名使用
        OrderDetail orderDetailOut = new OrderDetail();
        orderDetailOut.setUsePrice(userPriceAll);//使用金额
        orderDetailOut.setUseCourseCount(userCourseCountAll);//使用课时
        orderDetailOut.setOutPrice(residuePriceAll);//转出金额（包含了使用金额）
        orderDetailOut.setOutHouse(residueCourseCountAll);//转出课时(包含了使用课时)

        ResChangeSchoolReturn resChangeSchoolReurn = new ResChangeSchoolReturn();
        resChangeSchoolReurn.setOrderApply(returnOrderApply);
        resChangeSchoolReurn.setOrderDetail(orderDetailOut);
        resChangeSchoolReurn.setCourse(outCourse);
        resChangeSchoolReurn.setCoursePricing(coursePricing);
        resChangeSchoolReurn.setResiduePriceAll(residuePriceAll);
        resChangeSchoolReurn.setResidueCourseCountAll(residueCourseCountAll);
        return new Result(Code.OK, resChangeSchoolReurn, "成功");
    }


    /**
     * 退费（剩余加使用）
     * @param changeSchoolDetailParam
     * @param orderDetailList
     * @return
     */
    public Result returnOremiumForResidueAndUse(ChangeSchoolDetail changeSchoolDetailParam, List<OrderDetail> orderDetailList) {

        Long orderNo = idWorker.nextId();

        LocalDate nowDate = LocalDate.now();
        OrderApply returnOrderApply = new OrderApply();//退费
        OrderTransfer orderTransfer = new OrderTransfer();
        orderTransfer.setId(idWorker.nextId());
        Organization outSchool = iOrganizationService.getById(changeSchoolDetailParam.getOutSchoolId());
        Staff staff = new Staff();
        if (changeSchoolDetailParam.getCreatedId() == null || changeSchoolDetailParam.getCreatedId().equals(1568138350324350975L)) {
            staff.setId(changeSchoolDetailParam.getCreatedId());
            staff.setName("超级管理员");
        } else {
            staff = iStaffService.getById(changeSchoolDetailParam.getCreatedId());
        }

        returnOrderApply.setId(idWorker.nextId());
        returnOrderApply.setOrderNo(orderNo.toString());
        Integer receiptNo = CommonUtil.getReceiptNo(7);
        returnOrderApply.setReceiptNo(receiptNo.toString());
        returnOrderApply.setChangeSchoolDetailId(changeSchoolDetailParam.getId());//转校详情id
        returnOrderApply.setLessonType(1);
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);//退费和转校两个都设置为一样的状态
        returnOrderApply.setCostType(2);//1收入，2支出
        returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
        returnOrderApply.setStudentId(changeSchoolDetailParam.getStudentId());
        returnOrderApply.setYearPart(changeSchoolDetailParam.getYearPart());
        returnOrderApply.setQuarterNum(changeSchoolDetailParam.getQuarterNum());
        //returnOrderApply.setHandleSchoolId(changeSchoolDetailParam.getInSchoolId());
        returnOrderApply.setHandleSchoolName(outSchool.getName());
        returnOrderApply.setSchoolId(changeSchoolDetailParam.getOutSchoolId());//所属校区
        returnOrderApply.setHandleSchoolId(changeSchoolDetailParam.getOutSchoolId());
        returnOrderApply.setHandlePersonId(changeSchoolDetailParam.getCreatedId());
        returnOrderApply.setHandlePersonName(staff.getName());
        returnOrderApply.setHandlePersonName(staff.getName());
        returnOrderApply.setHandleDate(nowDate);
        returnOrderApply.setCreatedId(changeSchoolDetailParam.getCreatedId());
        returnOrderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
        returnOrderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
        returnOrderApply.setSignType(3);

        List<OrderTransferDetail> orderTransferDetailList = new ArrayList<>();
        Long outCourseId = null;
        if (orderDetailList.size() == 0) {
            return new Result(Code.ERROR, "", "剩余课时为0，不能转校");
            //throw  new CommonException(ResultCode.COURSE_ZERO);
        }


        Integer residueCourseCountAll = 0;//剩余加使用课次

        BigDecimal userPriceAll = new BigDecimal(0);
        Integer userCourseCountAll = 0;
        Integer yearClassId = null;
        Long subjectsId = null;
        for (OrderDetail orderDetailOld : orderDetailList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(orderDetailOld, orderDetail);
            outCourseId = orderDetail.getCourseId();
            Integer turnOutCourseCountNow = orderDetail.getResidueCourseCount()+orderDetail.getUseCourseCount();
            residueCourseCountAll += turnOutCourseCountNow;//使用加剩余课时
            yearClassId = orderDetailOld.getYearClassId();
            subjectsId = orderDetailOld.getSubjectsId();
        }

        returnOrderApply.setYearClassId(yearClassId);
        if (subjectsId != null){
            returnOrderApply.setSubjectsIdStr(subjectsId.toString());
        }

        changeSchoolDetailParam.setTurnOutHouse(residueCourseCountAll);

        Course outCourse = iCourseService.getById(outCourseId);
        if (outCourse == null) {
            //System.out.println("课程为空");
            return new Result(Code.ERROR, "", "转出校区课程为空");
        }

        CoursePricing coursePricing = this.getCoursePricing(outCourse, changeSchoolDetailParam.getTurnOutHouse(), changeSchoolDetailParam.getInSchoolId());
        if (coursePricing == null) {
            return new Result(Code.ERROR, "", "转入校区课程价格为空");
            //throw  new CommonException(ResultCode.COURSE_PRICE_NOT);
        }


        residueCourseCountAll = 0;//剩余加使用课次
        BigDecimal residuePriceAll = new BigDecimal(0);//剩余加使用金额

        for (OrderDetail orderDetailOld : orderDetailList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(orderDetailOld, orderDetail);

            outCourseId = orderDetail.getCourseId();
            //residuePriceAll = residuePriceAll.add(orderDetail.getResiduePrice());
            //residueCourseCountAll += orderDetail.getResidueCourseCount();

            userPriceAll = userPriceAll.add(orderDetail.getUsePrice());
            userCourseCountAll += orderDetail.getUseCourseCount();

            BigDecimal turnOutPriceNow = orderDetail.getResiduePrice().add(orderDetail.getUsePrice());
            Integer turnOutCourseCountNow = orderDetail.getResidueCourseCount()+orderDetail.getUseCourseCount();

            residuePriceAll = residuePriceAll.add(turnOutPriceNow);//使用加剩余金额
            residueCourseCountAll += turnOutCourseCountNow;//使用加剩余课时

            OrderTransferDetail orderTransferDetail = new OrderTransferDetail();
            orderTransferDetail.setOldOrderDetailId(orderDetail.getId());
            orderTransferDetail.setOldOrderId(orderDetail.getOrderId());
            orderTransferDetail.setOrderId(returnOrderApply.getId());
            orderTransferDetail.setOrderType(OrderTypeEnum.ORDER_TYPE_REFUND);
            orderTransferDetail.setOutHouse(orderDetail.getResidueCourseCount());
            orderTransferDetail.setOutPrice(orderDetail.getResiduePrice());
            orderTransferDetailList.add(orderTransferDetail);


            //转出金额
            BigDecimal turnOutPrice = orderDetail.getTurnOutPrice().add(turnOutPriceNow);
            orderDetail.setTurnOutPrice(turnOutPrice);
            orderDetail.setUsePrice(BigDecimal.ZERO);
            orderDetail.setResiduePrice(new BigDecimal(0));

            //转出课时
            Integer turnOutHouse = orderDetail.getTurnOutHouse() + turnOutCourseCountNow;
            orderDetail.setTurnOutHouse(turnOutHouse);
            orderDetail.setResidueCourseCount(0);
            orderDetail.setUseCourseCount(0);
            iOrderDetailService.updateById(orderDetail);

        }
        orderTransfer.setOrderId(returnOrderApply.getId());
        orderTransfer.setOutSchoolId(changeSchoolDetailParam.getOutSchoolId());
        orderTransfer.setInSchoolId(changeSchoolDetailParam.getInSchoolId());
        orderTransfer.setOutGradeId(outCourseId);//转出课程id
        orderTransfer.setInGradeId(outCourseId);//转入课程id
        orderTransfer.setOutPrice(residuePriceAll);
        orderTransfer.setOutHouse(residueCourseCountAll / 3);//这里是课次，所以除3
        orderTransfer.setOutType(1);
        orderTransfer.setCreatedId(changeSchoolDetailParam.getCreatedId());
        orderTransfer.setOrderType(4);

        String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
        tradeContent += "转校退费：" + outCourse.getName() + "退" + orderTransfer.getOutHouse() + "课次，应退学费" + orderTransfer.getOutPrice() + "元";

        returnOrderApply.setTradeContent(tradeContent);
        returnOrderApply.setPrice(orderTransfer.getOutPrice());//设置退费金额
        returnOrderApply.setSolidPrice(orderTransfer.getOutPrice());//实收金额
        changeSchoolDetailParam.setTurnOutHouse(residueCourseCountAll);
        changeSchoolDetailParam.setTurnOutPrice(orderTransfer.getOutPrice());



        iOrderTransferService.save(orderTransfer);
        iOrderTransferDetailService.saveBatch(orderTransferDetailList);
        iOrderApplyService.save(returnOrderApply);
        //this.changeApply(changeSchoolDetailParam, returnOrderApply, outCourse, coursePricing);

        //报名使用
        OrderDetail orderDetailOut = new OrderDetail();
        orderDetailOut.setUsePrice(userPriceAll);//使用金额
        orderDetailOut.setUseCourseCount(userCourseCountAll);//使用课时
        orderDetailOut.setOutPrice(residuePriceAll);//转出金额（包含了使用金额）
        orderDetailOut.setOutHouse(residueCourseCountAll);//转出课时(包含了使用课时)

        ResChangeSchoolReturn resChangeSchoolReurn = new ResChangeSchoolReturn();
        resChangeSchoolReurn.setOrderApply(returnOrderApply);
        resChangeSchoolReurn.setOrderDetail(orderDetailOut);
        resChangeSchoolReurn.setCourse(outCourse);
        resChangeSchoolReurn.setCoursePricing(coursePricing);
        resChangeSchoolReurn.setResiduePriceAll(residuePriceAll);
        resChangeSchoolReurn.setResidueCourseCountAll(residueCourseCountAll);
        return new Result(Code.OK, resChangeSchoolReurn, "成功");
    }


    /**
     * 转校报名（只转剩余课时的）
     * @param changeSchoolDetailParam
     * @param returnOrderApply
     * @param course
     * @param coursePricing
     * @param orderDetailOut
     * @param type 1为剩余转，2剩余加使用转（为2时，报名时剩余课时等于课时减掉使用课时）
     * @return
     */
    public Result changeApply(ChangeSchoolDetail changeSchoolDetailParam, OrderApply returnOrderApply, Course course, CoursePricing coursePricing, OrderDetail orderDetailOut,Integer type) {

        LocalDate nowDate = LocalDate.now();
        iStudentSchoolService.addData(changeSchoolDetailParam.getInSchoolId(),changeSchoolDetailParam.getStudentId());

        Integer useCourseHouse = orderDetailOut.getUseCourseCount();
        BigDecimal usePirce = orderDetailOut.getUsePrice();

        OrderApply orderApply = new OrderApply();
        BeanUtils.copyProperties(returnOrderApply, orderApply);
        orderApply.setId(idWorker.nextId());

        orderApply.setChangeSchoolDetailId(changeSchoolDetailParam.getId());
        orderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
        orderApply.setApplyType(null);
        orderApply.setCostType(1);
        orderApply.setSchoolId(changeSchoolDetailParam.getInSchoolId());
        Organization inSchool = iOrganizationService.getById(changeSchoolDetailParam.getInSchoolId());
        orderApply.setHandleSchoolId(changeSchoolDetailParam.getInSchoolId());
        orderApply.setHandleSchoolName(inSchool.getName());
        orderApply.setYearClassId(course.getYearClassId().getKey());
        orderApply.setSubjectsIdStr(course.getSubjectsId().toString());

        String coursePriceName = coursePricing.getCount() + coursePricing.getCountUnit() + "=" + coursePricing.getAllPrice() + "元";

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setChangeSchoolDetailId(changeSchoolDetailParam.getId());
        orderDetail.setOrderId(orderApply.getId());
        orderDetail.setSchoolId(changeSchoolDetailParam.getInSchoolId());
        orderDetail.setStudentId(orderApply.getStudentId());
        orderDetail.setLessonType(1);
        orderDetail.setCourseId(course.getId());
        orderDetail.setCourseName(course.getName());
        orderDetail.setSubjectsId(course.getSubjectsId());
        orderDetail.setCoursePriceId(coursePricing.getId());
        orderDetail.setCoursePriceName(coursePriceName);
        orderDetail.setYearClassId(course.getYearClassId().getKey());



        orderDetail.setCount(orderDetailOut.getOutHouse() / coursePricing.getCount());
        orderDetail.setAllCourseCount(orderDetailOut.getOutHouse());
         //orderDetailOut.getOutHouse() - orderDetailOut.getUseCourseCount();//剩余课时= 转出-使用

        orderDetail.setPrice(orderDetailOut.getOutPrice());
        orderDetail.setSolidPrice(orderDetailOut.getOutPrice());

        BigDecimal residuePrice = orderDetailOut.getOutPrice();//orderDetailOut.getOutPrice().subtract(orderDetailOut.getUsePrice());
        Integer residueCourseCount = orderDetailOut.getOutHouse();
        if (type.equals(2)){
            residuePrice = orderDetailOut.getOutPrice().subtract(usePirce);
            residueCourseCount = orderDetailOut.getOutHouse() - useCourseHouse;
            orderDetail.setUseCourseCount(useCourseHouse);
            orderDetail.setUsePrice(usePirce);
        }
        orderDetail.setResidueCourseCount(residueCourseCount);
        orderDetail.setResiduePrice(residuePrice);
        //orderDetail.setUseCourseCount(orderDetailOut.getUseCourseCount());

        orderDetail.setServePrice(coursePricing.getServePrice());
        orderDetail.setMaterialsPrice(coursePricing.getMaterialsPrice());
        orderDetail.setYearPart(changeSchoolDetailParam.getYearPart());
        orderDetail.setQuarterNum(changeSchoolDetailParam.getQuarterNum());
        Integer yearAndQuarter = Integer.parseInt(changeSchoolDetailParam.getYearPart() + "" + changeSchoolDetailParam.getQuarterNum());
        orderDetail.setYearAndQuarter(yearAndQuarter);
        orderDetail.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER);
        orderDetail.setHandleDate(nowDate);
        orderDetail.setCreatedId(changeSchoolDetailParam.getCreatedId());

        String tradeContent = "转校报名：" + course.getName() + "," + orderDetail.getPrice();
        tradeContent += "(" + coursePricing.getCountUnit() + ")*" + orderDetail.getCount() + "=" + orderDetail.getPrice() + "元";
        orderApply.setTradeContent(tradeContent);

        iOrderApplyService.save(orderApply);
        iOrderDetailService.save(orderDetail);

        //更新转出校区智能课或者刷题班的课次为零
        //iOrderDetailService.updateResidueCourse(changeSchoolDetailParam.getOutSchoolId(),orderDetail.getStudentId(),orderDetail.getSubjectsId(),orderDetail.getYearPart(),orderDetail.getQuarterNum(),orderDetail.getLessonType());
        //转入校区智能课或者精品课添加
        //iOrderDetailService.addOrderApply(orderDetail.getYearPart(), orderDetail.getQuarterNum(), orderDetail.getSchoolId(), orderDetail.getSubjectsId(), orderDetail.getLessonType(), orderDetail.getStudentId());

        ResChangeSchoolReturn resChangeSchoolReurn = new ResChangeSchoolReturn();
        resChangeSchoolReurn.setOrderApply(orderApply);
        resChangeSchoolReurn.setOrderDetail(orderDetail);
        resChangeSchoolReurn.setCourse(course);
        return new Result(Code.OK, resChangeSchoolReurn, "");
    }


    /**
     * 全部转出（剩余加使用）
     * @param changeSchoolDetailParam
     * @return
     * @throws ParseException
     */
    public Result returnAndApply(ChangeSchoolDetail changeSchoolDetailParam) throws ParseException {

        Integer lessonType = 1;

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("year_part", changeSchoolDetailParam.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", changeSchoolDetailParam.getQuarterNum());
        orderDetailQueryWrapper.eq("school_id", changeSchoolDetailParam.getOutSchoolId());
        orderDetailQueryWrapper.eq("subjects_id", changeSchoolDetailParam.getSubjectsId());
        orderDetailQueryWrapper.eq("student_id", changeSchoolDetailParam.getStudentId());
        orderDetailQueryWrapper.eq("lesson_type", lessonType);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.and(i->i.gt("residue_course_count", 0).or(j->j.gt("use_course_count",0)));

        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);

        Result result = this.returnOremiumForResidueAndUse(changeSchoolDetailParam, orderDetailList);
        if (result.getCode().equals(Code.OK)) {
            ResChangeSchoolReturn resChangeSchoolReurn = (ResChangeSchoolReturn) result.getData();
            Result resultApply = this.changeApply(changeSchoolDetailParam, resChangeSchoolReurn.getOrderApply(), resChangeSchoolReurn.getCourse(), resChangeSchoolReurn.getCoursePricing(), resChangeSchoolReurn.getOrderDetail(),2);
            if (resultApply.getCode().equals(Code.OK)) {
                changeSchoolDetailParam.setStatus(1);//0未转校，1已转校，2转校失败（操作转校时才使用）
                changeSchoolDetailParam.setTurnOutHouse(resChangeSchoolReurn.getResidueCourseCountAll());
                changeSchoolDetailParam.setTurnOutPrice(resChangeSchoolReurn.getResiduePriceAll());
                ResChangeSchoolReturn resApplyReturn = (ResChangeSchoolReturn) resultApply.getData();

                //报名完成添加其它数据
                this.updateChangeSchoolDataForResidue(changeSchoolDetailParam,resApplyReturn.getOrderDetail(),2);
                iChangeSchoolDetailService.updateById(changeSchoolDetailParam);
                return new Result(Code.OK, "成功");
            } else {
                changeSchoolDetailParam.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
                changeSchoolDetailParam.setRemark(result.getMessage());
                iChangeSchoolDetailService.updateById(changeSchoolDetailParam);
                return new Result(Code.ERROR, "失败");
            }
        } else {
            changeSchoolDetailParam.setStatus(2);//0未转校，1已转校，2转校失败（操作转校时才使用）
            changeSchoolDetailParam.setRemark(result.getMessage());
            iChangeSchoolDetailService.updateById(changeSchoolDetailParam);
            return new Result(Code.ERROR, "失败");
        }
    }


    /**
     * 退费与报名（全部转出）【此方法作废，需要调整不需要订单全部移过去】
     *
     * @return
     */
    public Result returnAndApplyObs(ChangeSchoolDetail changeSchoolDetailParam) throws ParseException {

        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

        Organization inSchool = iOrganizationService.getById(changeSchoolDetailParam.getInSchoolId());

        Integer lessonType = 1;
        QueryWrapper<OrderApply> orderApplyQueryWrapper = new QueryWrapper<>();
        orderApplyQueryWrapper.eq("year_part", changeSchoolDetailParam.getYearPart());
        orderApplyQueryWrapper.eq("quarter_num", changeSchoolDetailParam.getQuarterNum());
        orderApplyQueryWrapper.eq("school_id", changeSchoolDetailParam.getOutSchoolId());
        orderApplyQueryWrapper.eq("student_id", changeSchoolDetailParam.getStudentId());
        orderApplyQueryWrapper.eq("subjects_id_str",changeSchoolDetailParam.getSubjectsId());
        orderApplyQueryWrapper.eq("lesson_type", lessonType);
        orderApplyQueryWrapper.ne("status", 3);
        List<OrderApply> orderApplyList = iOrderApplyService.list(orderApplyQueryWrapper);
        for (OrderApply orderApply : orderApplyList) {
            Long orderId = orderApply.getId();
            OrderApply orderApplyNew = new OrderApply();
            BeanUtils.copyProperties(orderApply, orderApplyNew);
            iStudentSchoolService.addData(changeSchoolDetailParam.getInSchoolId(),orderApply.getStudentId());

            orderApplyNew.setId(idWorker.nextId());
            orderApplyNew.setOutId(orderId);
            orderApplyNew.setSchoolId(changeSchoolDetailParam.getInSchoolId());
            orderApplyNew.setChangeSchoolDetailId(changeSchoolDetailParam.getId());


            //退费
            if (orderApply.getOrderType().equals(OrderTypeEnum.ORDER_TYPE_REFUND)) {
                QueryWrapper<OrderTransfer> orderTransferQueryWrapper = new QueryWrapper<>();
                orderTransferQueryWrapper.eq("order_id", orderId);
                List<OrderTransfer> orderTransferList = iOrderTransferService.list(orderTransferQueryWrapper);
                for (OrderTransfer orderTransfer : orderTransferList) {
                    OrderTransfer orderTransferNew = new OrderTransfer();
                    BeanUtils.copyProperties(orderTransfer, orderTransferNew);

                    orderTransferNew.setId(idWorker.nextId());
                    orderTransferNew.setOrderId(orderApplyNew.getId());
                    iOrderTransferService.save(orderTransferNew);
                }

                QueryWrapper<OrderTransferDetail> orderTransferDetailQueryWrapper = new QueryWrapper<>();
                orderTransferDetailQueryWrapper.eq("order_id", orderId);
                List<OrderTransferDetail> orderTransferDetailList = iOrderTransferDetailService.list(orderTransferDetailQueryWrapper);
                for (OrderTransferDetail orderTransferDetail : orderTransferDetailList) {
                    OrderTransferDetail orderTransferDetailNew = new OrderTransferDetail();
                    BeanUtils.copyProperties(orderTransferDetail, orderTransferDetailNew);
                    orderTransferDetailNew.setId(idWorker.nextId());
                    orderTransferDetailNew.setOrderId(orderApplyNew.getId());
                    iOrderTransferDetailService.save(orderTransferDetailNew);
                }
            } else {
                QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                orderDetailQueryWrapper.eq("order_id", orderId);
                List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
                Integer resCourseCount = 0;
                for (OrderDetail orderDetail : orderDetailList) {
                    resCourseCount += orderDetail.getResidueCourseCount()+orderDetail.getUseCourseCount();
                }

                String tradeContent = "转校报名：";
                if (resCourseCount>0){
                    //退费
                    this.returnOremium(changeSchoolDetailParam, orderDetailList);
                }

                for (OrderDetail orderDetail : orderDetailList) {
                    //QueryWrapper<OrderDetail> orderDetailQueryWrapper

                    OrderDetail orderDetailNew = new OrderDetail();
                    BeanUtils.copyProperties(orderDetail, orderDetailNew);
                    orderDetailNew.setId(idWorker.nextId());
                    orderDetailNew.setOrderId(orderApplyNew.getId());
                    orderDetailNew.setSchoolId(changeSchoolDetailParam.getInSchoolId());
                    orderDetailNew.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
                    orderDetailNew.setOutId(orderDetail.getId());
                    orderDetailNew.setChangeSchoolDetailId(changeSchoolDetailParam.getId());
                    orderDetailNew.setCreatedAt(dateTimeNow);
                    iOrderDetailService.save(orderDetailNew);//添加订单

                    Course course = iCourseService.getById(orderDetail.getCourseId());
                    CoursePricing coursePricing = this.getCoursePricing(course, orderDetail.getResidueCourseCount() + orderDetail.getUseCourseCount(), changeSchoolDetailParam.getInSchoolId());
                    tradeContent += course.getName() + "," + orderDetail.getPrice();
                    tradeContent += "(" + coursePricing.getCountUnit() + ")*" + orderDetail.getCount() + "=" + orderDetail.getPrice() + "元";
                    this.mvStudentGradeData(changeSchoolDetailParam,orderDetail,orderDetailNew);
                    this.mvRecordCourse(changeSchoolDetailParam,orderDetail,orderDetailNew);
                }

                //orderApply.setTradeContent(tradeContent);

                QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
                enrollInfoQueryWrapper.eq("order_id", orderId);
                List<EnrollInfo> enrollInfoList = iEnrollInfoService.list(enrollInfoQueryWrapper);
                for (EnrollInfo enrollInfo : enrollInfoList) {
                    enrollInfo.setChangeSchoolDetailId(changeSchoolDetailParam.getId());
                    EnrollInfo enrollInfoNew = new EnrollInfo();
                    BeanUtils.copyProperties(enrollInfo, enrollInfoNew);

                    enrollInfoNew.setOutId(enrollInfo.getId());
                    enrollInfoNew.setId(idWorker.nextId());
                    enrollInfoNew.setOrderId(orderApplyNew.getId());
                    enrollInfoNew.setSchoolId(changeSchoolDetailParam.getInSchoolId());
                    enrollInfoNew.setSchoolName(inSchool.getName());
                    iEnrollInfoService.save(enrollInfoNew);

                    iEnrollInfoService.updateById(enrollInfo);
                    iEnrollInfoService.updateDeleted(enrollInfo.getId(),2);

                }

                QueryWrapper<DealInfo> dealInfoQueryWrapper = new QueryWrapper<>();
                dealInfoQueryWrapper.eq("order_id", orderId);
                List<DealInfo> dealInfoList = iDealInfoService.list(dealInfoQueryWrapper);
                for (DealInfo dealInfo : dealInfoList) {
                    dealInfo.setChangeSchoolDetailId(changeSchoolDetailParam.getId());

                    DealInfo dealInfoNew = new DealInfo();
                    BeanUtils.copyProperties(dealInfo, dealInfoNew);
                    dealInfoNew.setId(idWorker.nextId());
                    dealInfoNew.setSchoolId(inSchool.getId());
                    dealInfoNew.setOutId(dealInfo.getId());
                    dealInfoNew.setOrderId(orderApplyNew.getId());
                    iDealInfoService.save(dealInfoNew);
                    //dealInfo.setSchoolId(inSchool.getId());
                    iDealInfoService.updateById(dealInfo);
                    iDealInfoService.updateDeleted(dealInfo.getId(),2);
                }

                QueryWrapper<OrderPayAccount> orderPayAccountQueryWrapper = new QueryWrapper<>();
                orderPayAccountQueryWrapper.eq("order_id", orderId);
                List<OrderPayAccount> orderPayAccountList = iOrderPayAccountService.list(orderPayAccountQueryWrapper);
                for (OrderPayAccount orderPayAccount : orderPayAccountList) {
                    OrderPayAccount orderPayAccountNew = new OrderPayAccount();
                    BeanUtils.copyProperties(orderPayAccount, orderPayAccountNew);
                    orderPayAccountNew.setId(idWorker.nextId());
                    orderPayAccountNew.setOrderId(orderApplyNew.getId());
                    iOrderPayAccountService.save(orderPayAccountNew);
                }



                //优惠
                QueryWrapper<OrderDisDetail> orderDisDetailQueryWrapper = new QueryWrapper<>();
                orderDisDetailQueryWrapper.eq("order_id", orderId);
                List<OrderDisDetail> orderDisDetailList = iOrderDisDetailService.list(orderDisDetailQueryWrapper);
                for (OrderDisDetail orderDisDetail : orderDisDetailList) {
                    OrderDisDetail orderDisDetailNew = new OrderDisDetail();
                    BeanUtils.copyProperties(orderDisDetail, orderDisDetailNew);
                    orderDisDetailNew.setId(idWorker.nextId());
                    orderDisDetailNew.setOrderId(orderApplyNew.getId());
                    iOrderDisDetailService.save(orderDisDetailNew);
                }

                QueryWrapper<OrderDisClan> disClanQueryWrapper = new QueryWrapper<>();
                disClanQueryWrapper.eq("order_id", orderId);
                List<OrderDisClan> orderDisClanList = iOrderDisClanService.list(disClanQueryWrapper);
                for (OrderDisClan orderDisClan : orderDisClanList) {
                    OrderDisClan orderDisClanNew = new OrderDisClan();
                    BeanUtils.copyProperties(orderDisClan, orderDisClanNew);
                    orderDisClanNew.setId(idWorker.nextId());
                    orderDisClanNew.setOrderId(orderApplyNew.getId());
                    iOrderDisClanService.save(orderDisClanNew);
                }

                QueryWrapper<OrderDisPrice> orderDisPriceQueryWrapper = new QueryWrapper<>();
                orderDisPriceQueryWrapper.eq("order_id", orderId);
                List<OrderDisPrice> orderDisPriceList = iOrderDisPriceService.list(orderDisPriceQueryWrapper);
                for (OrderDisPrice orderDisPrice : orderDisPriceList) {
                    OrderDisPrice orderDisPriceNew = new OrderDisPrice();
                    BeanUtils.copyProperties(orderDisPrice, orderDisPriceNew);
                    orderDisPriceNew.setId(idWorker.nextId());
                    orderDisPriceNew.setOrderId(orderApplyNew.getId());
                    iOrderDisPriceService.save(orderDisPriceNew);
                }


                orderApplyNew.setApplyType(OrderTypeEnum.NO);
                //orderApplyNew.setTradeContent(tradeContent);
            }
            orderApplyNew.setHandleSchoolId(changeSchoolDetailParam.getInSchoolId());
            orderApplyNew.setHandleSchoolName(inSchool.getName());
            orderApplyNew.setCreatedAt(dateTimeNow);
            //orderApplyNew.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER_SCHOOL);
            iOrderApplyService.save(orderApplyNew);

        }
        return new Result(Code.OK, "成功");
    }


    /**
     * 自动添加转入校区分班信息与排课信息【按老师剩余转】
     * @param changeSchoolDetail
     * @param orderDetail
     * @param type
     * @return
     * @throws ParseException
     */
    public boolean updateChangeSchoolDataForResidue(ChangeSchoolDetail changeSchoolDetail,OrderDetail orderDetail,Integer type) throws ParseException {

        Organization inSchoolInfo = iOrganizationService.getById(changeSchoolDetail.getInSchoolId());
        Integer lessonType = 1;
        /**
         * 找出最后一条分班信息
         */
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        studentGradeQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        studentGradeQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        studentGradeQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
        studentGradeQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.ne("status", 3);
        studentGradeQueryWrapper.eq("deleted", 0);
        studentGradeQueryWrapper.in("reading_status",0,1, 2,3,4, 5,6);
        //studentGradeQueryWrapper.and(i -> i.eq("reading_status", 1).or(j -> j.gt("use_course_count", 0)));
        studentGradeQueryWrapper.orderByDesc("id");
        studentGradeQueryWrapper.last("limit 1");

        Integer userCourseHouse = 0;
        if (type.equals(2)){
            userCourseHouse = orderDetail.getUseCourseCount();
        }
        Grade grade = null;
        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        for (StudentGrade studentGrade : studentGradeList) {
            Long teacherId = 0L;
            if (changeSchoolDetail.getChangeTeacherId() != null && changeSchoolDetail.getChangeTeacherId() != 0L) {
                teacherId = changeSchoolDetail.getChangeTeacherId();
            }else {
                Grade gradeOld = iGradeService.getById(studentGrade.getGradeId());
                teacherId = gradeOld.getTeacherId();
            }
            grade = iGradeService.createdForChangeSchool(studentGrade.getGradeId(), changeSchoolDetail.getInSchoolId(), teacherId, changeSchoolDetail,false);

            QueryWrapper<StudentGrade> studentGradeQueryWrapperChange = new QueryWrapper<>();
            studentGradeQueryWrapperChange.eq("student_id", changeSchoolDetail.getStudentId());
            studentGradeQueryWrapperChange.eq("school_id", changeSchoolDetail.getInSchoolId());
            studentGradeQueryWrapperChange.eq("grade_id", grade.getId());
            studentGradeQueryWrapperChange.last("limit 1");
            StudentGrade studentGradeAt = iStudentGradeService.getOne(studentGradeQueryWrapperChange);
            if (studentGradeAt == null){
                studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
                Grade gradeOld = iGradeService.getById(studentGrade.getGradeId());
                StudentGrade studentGradeNew = new StudentGrade();
                BeanUtils.copyProperties(studentGrade, studentGradeNew);

                studentGradeNew.setId(idWorker.nextId());
                studentGradeNew.setOutId(studentGrade.getId());
                studentGradeNew.setCreatedAt(LocalDateTime.now().withNano(0));
                studentGradeNew.setSchoolId(changeSchoolDetail.getInSchoolId());
                studentGradeNew.setOrderDetailId(orderDetail.getId());
                studentGradeNew.setUseCourseCount(userCourseHouse);
                studentGradeNew.setCourseId(orderDetail.getCourseId());
                studentGradeNew.setCreatedId(changeSchoolDetail.getCreatedId());
                studentGradeNew.setGradeId(grade.getId());
                studentGradeNew.setReadingStatus(studentGrade.getReadingStatus());
                //studentGradeNew.setIsLast(studentGrade.getIsLast());
                iStudentGradeService.save(studentGradeNew);
            }else {

            }

            //Integer outUseCourseCount = studentGrade.getUseCourseCount() + studentGrade.getOutUseCourseCount();
            //Integer userCourseCount = 0;
            //studentGrade.setOutUseCourseCount(outUseCourseCount);//累计转出课次
            //studentGrade.setUseCourseCount(userCourseCount);

            //studentGrade.setDeleted(2);
            studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
            studentGrade.setStatus(StatusStudentGradeEnum.TURN);
            studentGrade.setReadingStatus(ReadingStatusEnum.FINISH);
            studentGrade.setIsLast(0);
            //studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));
            iStudentGradeService.updateById(studentGrade);

            //删除原有数据
            studentGradeQueryWrapper.clear();
            studentGradeQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
            studentGradeQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
            studentGradeQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
            studentGradeQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
            studentGradeQueryWrapper.eq("lesson_type", lessonType);
            studentGradeQueryWrapper.ne("status", 3);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.in("reading_status",0,1, 2,3,4, 5,6);
            iStudentGradeService.remove(studentGradeQueryWrapper);


            //iStudentGradeService.updateDeleted(studentGrade.getId(), 2);
        }

        /**
         * 缺课未补
         */
        QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();
        lackCourseLogQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        lackCourseLogQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        lackCourseLogQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        lackCourseLogQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        lackCourseLogQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
        lackCourseLogQueryWrapper.eq("lesson_type", lessonType);
        if (type.equals(1)){
            lackCourseLogQueryWrapper.ne("is_repair",1);//未补的
        }

        List<LackCourseLog> lackCourseLogList = iLackCourseLogService.list(lackCourseLogQueryWrapper);
        for (LackCourseLog lackCourseLog : lackCourseLogList) {
            lackCourseLog.setChangeSchoolDetailId(changeSchoolDetail.getId());

            LackCourseLog lackCourseLogNew = new LackCourseLog();
            BeanUtils.copyProperties(lackCourseLog, lackCourseLogNew);
            lackCourseLogNew.setId(idWorker.nextId());
            if (grade != null){
                lackCourseLogNew.setGradeId(grade.getId());
            }
            lackCourseLogNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            lackCourseLogNew.setOutId(lackCourseLog.getId());
            iLackCourseLogService.save(lackCourseLogNew);

            //删除原有数据
            //lackCourseLog.setDeleted(2);
            iLackCourseLogService.updateById(lackCourseLog);
            iLackCourseLogService.updateDeleted(lackCourseLog.getId(), 2);
        }

        /**
         * 请假未补
         */
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        recordCourseQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        recordCourseQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        recordCourseQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        recordCourseQueryWrapper.eq("quarter", changeSchoolDetail.getQuarterNum());
        recordCourseQueryWrapper.eq("lesson_type", lessonType);
        if (type.equals(1)){
            recordCourseQueryWrapper.eq("status",2);
            recordCourseQueryWrapper.ne("is_repair",1);//请假未补的
        }

        recordCourseQueryWrapper.orderByAsc("id");
        List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
        for (RecordCourse recordCourse : recordCourseList) {
            recordCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());

            RecordCourse recordCourseNew = new RecordCourse();
            BeanUtils.copyProperties(recordCourse, recordCourseNew);

            recordCourseNew.setId(idWorker.nextId());
            recordCourseNew.setOutId(recordCourse.getId());
            recordCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            recordCourseNew.setSchoolName(inSchoolInfo.getName());
            recordCourseNew.setOutId(recordCourse.getId());
            recordCourseNew.setCreatedAt(LocalDateTime.now().withNano(0));
            recordCourseNew.setOrderDetailId(orderDetail.getId());
            Integer courseType = recordCourse.getCourseType();

            QueryWrapper<RecordCourseLack> recordCourseLackQueryWrapper = new QueryWrapper<>();
            RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCourse.getId());
            if (recordCourseLack != null){
                recordCourseLack.setOrderDetailId(orderDetail.getId());
                iRecordCourseLackService.updateById(recordCourseLack);
            }


            //课程类别：1精品课（正常排课），3补课，4调课，5消课,6缺课补课
            if (courseType.equals(1)) {
                CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOneForId(recordCourse.getSchedulingDetailId());
                if (courseSchedulingDetail != null) {
                    CourseSchedulingDetail courseSchedulingDetailOut = iCourseSchedulingDetailService.getOneForOutId(courseSchedulingDetail.getId());
                    if (courseSchedulingDetailOut != null) {
                        recordCourseNew.setSchedulingDetailId(courseSchedulingDetailOut.getId());
                    } else {
                        recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                    }
                }

            } else if (courseType.equals(3) || courseType.equals(4) || courseType.equals(5) || courseType.equals(6)) {
                RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getSchedulingDetailId());
                if (repairCourse != null) {
                    repairCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());
                    RepairCourse repairCourseNew = new RepairCourse();
                    BeanUtils.copyProperties(repairCourse, repairCourseNew);
                    repairCourseNew.setId(idWorker.nextId());
                    repairCourseNew.setOutId(repairCourse.getId());
                    repairCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());

                    if (courseType.equals(6)) {
                        LackCourseLog lackCourseLog = iLackCourseLogService.getOneForId(repairCourse.getRecordCourseId());
                        if (lackCourseLog != null) {
                            LackCourseLog lackCourseLogOut = iLackCourseLogService.getOneForOutId(lackCourseLog.getId());
                            if (lackCourseLogOut != null) {
                                repairCourseNew.setRecordCourseId(lackCourseLogOut.getId());
                            }
                        }
                    }
                    recordCourseNew.setSchedulingDetailId(repairCourseNew.getId());
                    iRepairCourseService.save(repairCourseNew);
                    //删除原有数据
                    //repairCourse.setDeleted(2);
                    iRepairCourseService.updateById(repairCourse);
                    iRepairCourseService.updateDeleted(recordCourse.getId(), 2);
                } else {
                    recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                }
            }

            //删除原有数据
            //recordCourse.setDeleted(2);
            iRecordCourseService.updateById(recordCourse);
            iRecordCourseService.updateDeleted(recordCourse.getId(), 2);

            iRecordCourseService.save(recordCourseNew);


            QueryWrapper<RecordCost> recordCostQueryWrapper = new QueryWrapper<>();
            recordCostQueryWrapper.eq("record_course_id", recordCourse.getId());
            List<RecordCost> recordCostList = iRecordCostService.list(recordCostQueryWrapper);
            for (RecordCost recordCost : recordCostList) {
                RecordCost recordCostNew = new RecordCost();
                BeanUtils.copyProperties(recordCost, recordCostNew);
                recordCostNew.setId(idWorker.nextId());
                recordCostNew.setRecordCourseId(recordCourseNew.getId());
                iRecordCostService.save(recordCostNew);

                //删除原有数据
                //recordCost.setDeleted(2);
                iRecordCostService.updateById(recordCost);
                iRecordCostService.updateDeleted(recordCost.getId(), 2);
            }
            this.mvRecordCourseLack(recordCourse,recordCourseNew,changeSchoolDetail);
        }

        //转移智能课与刷题班
        this.mvOtherCourseDataForTeacher(changeSchoolDetail);
        return true;
    }



    /**
     * 自动添加转入校区分班信息与排课信息【按老师全部转】
     * @param changeSchoolDetail
     * @return
     * @throws ParseException
     */
    public boolean updateChangeSchoolDataAll(ChangeSchoolDetail changeSchoolDetail) throws ParseException {

        Organization inSchoolInfo = iOrganizationService.getById(changeSchoolDetail.getInSchoolId());
        Integer lessonType = 1;
        /**
         * 找出分班信息
         */
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        studentGradeQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        studentGradeQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        studentGradeQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
        studentGradeQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.ne("status", 3);
        studentGradeQueryWrapper.eq("deleted", 0);
        //studentGradeQueryWrapper.and(i -> i.eq("reading_status", 1).or(j -> j.gt("use_course_count", 0)));

        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        for (StudentGrade studentGrade : studentGradeList) {
            studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
            Grade gradeOld = iGradeService.getById(studentGrade.getGradeId());
            if (gradeOld==null){
                continue;
            }
            StudentGrade studentGradeNew = new StudentGrade();
            BeanUtils.copyProperties(studentGrade, studentGradeNew);
            Grade grade = iGradeService.createdForChangeSchool(studentGrade.getGradeId(), changeSchoolDetail.getInSchoolId(), gradeOld.getTeacherId(), changeSchoolDetail,true);
            /*if (grade==null){
                continue;
            }*/

            Grade gradeChangeTeacher = null;
            if (changeSchoolDetail.getChangeTeacherId() != null && changeSchoolDetail.getChangeTeacherId() != 0L) {
                gradeChangeTeacher = iGradeService.createdForChangeSchool(studentGrade.getGradeId(), changeSchoolDetail.getInSchoolId(), changeSchoolDetail.getChangeTeacherId(), changeSchoolDetail,false);
            }

            studentGradeNew.setId(idWorker.nextId());
            studentGradeNew.setOutId(studentGrade.getId());
            //studentGradeNew.setCreatedAt(LocalDateTime.now().withNano(0));
            studentGradeNew.setSchoolId(changeSchoolDetail.getInSchoolId());

            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("out_id",studentGradeNew.getOrderDetailId());
            orderDetailQueryWrapper.last("limit 1");
            OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
            studentGradeNew.setOrderDetailId(orderDetail.getId());

            studentGradeNew.setCourseId(orderDetail.getCourseId());
            studentGradeNew.setCreatedId(changeSchoolDetail.getCreatedId());
            studentGradeNew.setGradeId(grade.getId());
            if (gradeChangeTeacher != null && (studentGrade.getReadingStatus().equals(ReadingStatusEnum.IN_READING) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.STOP))) {
                studentGradeNew.setReadingStatus(ReadingStatusEnum.TURN);
                studentGradeNew.setIsLast(0);
            }

            //studentGradeNew.setIsLast(studentGrade.getIsLast());
            studentGradeNew.setCreatedAt(studentGrade.getCreatedAt());
            iStudentGradeService.save(studentGradeNew);

            if (gradeChangeTeacher != null && (studentGrade.getReadingStatus().equals(ReadingStatusEnum.IN_READING) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.STOP))) {
                QueryWrapper<StudentGrade> studentGradeQueryWrapperChange = new QueryWrapper<>();
                studentGradeQueryWrapperChange.eq("student_id", changeSchoolDetail.getStudentId());
                studentGradeQueryWrapperChange.eq("grade_id", gradeChangeTeacher.getId());
                studentGradeQueryWrapperChange.last("limit 1");
                StudentGrade studentGradeChange = iStudentGradeService.getOne(studentGradeQueryWrapperChange);
                //存在就不添加
                if (studentGradeChange==null) {
                    StudentGrade studentGradeChangeTeacher = new StudentGrade();
                    BeanUtils.copyProperties(studentGradeNew, studentGradeChangeTeacher);

                    studentGradeChangeTeacher.setId(idWorker.nextId());
                    studentGradeChangeTeacher.setUseCourseCount(0);
                    studentGradeChangeTeacher.setOutUseCourseCount(0);
                    studentGradeChangeTeacher.setIsLast(1);
                    studentGradeChangeTeacher.setGradeId(gradeChangeTeacher.getId());
                    studentGradeChangeTeacher.setReadingStatus(ReadingStatusEnum.IN_READING);
                    studentGradeChangeTeacher.setCreatedAt(studentGrade.getCreatedAt());
                    iStudentGradeService.save(studentGradeChangeTeacher);
                }
                if (studentGradeChange !=null && studentGrade.getIsLast().equals(1)){
                    studentGradeChange.setCreatedAt(studentGrade.getCreatedAt());
                    iStudentGradeService.updateById(studentGradeChange);
                }
            }

            //删除原有数据
            Integer outUseCourseCount = studentGrade.getUseCourseCount() + studentGrade.getOutUseCourseCount();
            Integer userCourseCount = 0;
            studentGrade.setOutUseCourseCount(outUseCourseCount);//累计转出课次
            studentGrade.setUseCourseCount(userCourseCount);

            //studentGrade.setDeleted(2);
            studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
            iStudentGradeService.updateById(studentGrade);
            iStudentGradeService.updateDeleted(studentGrade.getId(), 2);
        }

        QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();
        lackCourseLogQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        lackCourseLogQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        lackCourseLogQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        lackCourseLogQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        lackCourseLogQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
        lackCourseLogQueryWrapper.eq("lesson_type", lessonType);

        List<LackCourseLog> lackCourseLogList = iLackCourseLogService.list(lackCourseLogQueryWrapper);
        for (LackCourseLog lackCourseLog : lackCourseLogList) {
            lackCourseLog.setChangeSchoolDetailId(changeSchoolDetail.getId());

            LackCourseLog lackCourseLogNew = new LackCourseLog();
            BeanUtils.copyProperties(lackCourseLog, lackCourseLogNew);
            lackCourseLogNew.setId(idWorker.nextId());
            lackCourseLogNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            lackCourseLogNew.setOutId(lackCourseLog.getId());
            iLackCourseLogService.save(lackCourseLogNew);

            //删除原有数据
            //lackCourseLog.setDeleted(2);
            iLackCourseLogService.updateById(lackCourseLog);
            iLackCourseLogService.updateDeleted(lackCourseLog.getId(), 2);
        }

        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        recordCourseQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        recordCourseQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        recordCourseQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        recordCourseQueryWrapper.eq("quarter", changeSchoolDetail.getQuarterNum());
        recordCourseQueryWrapper.eq("lesson_type", lessonType);
        recordCourseQueryWrapper.orderByAsc("id");
        List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
        for (RecordCourse recordCourse : recordCourseList) {
            recordCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());

            RecordCourse recordCourseNew = new RecordCourse();
            BeanUtils.copyProperties(recordCourse, recordCourseNew);

            recordCourseNew.setId(idWorker.nextId());
            recordCourseNew.setOutId(recordCourse.getId());
            recordCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            recordCourseNew.setSchoolName(inSchoolInfo.getName());
            recordCourseNew.setOutId(recordCourse.getId());
            recordCourseNew.setCreatedAt(LocalDateTime.now().withNano(0));

            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("out_id",recordCourseNew.getOrderDetailId());
            orderDetailQueryWrapper.last("limit 1");
            OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
            if (orderDetail!= null){
                recordCourseNew.setOrderDetailId(orderDetail.getId());
            }

            Integer courseType = recordCourse.getCourseType();

            //课程类别：1精品课（正常排课），3补课，4调课，5消课,6缺课补课
            if (courseType.equals(1)) {
                CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOneForId(recordCourse.getSchedulingDetailId());
                if (courseSchedulingDetail != null) {
                    CourseSchedulingDetail courseSchedulingDetailOut = iCourseSchedulingDetailService.getOneForOutId(courseSchedulingDetail.getId());
                    if (courseSchedulingDetailOut != null) {
                        recordCourseNew.setSchedulingDetailId(courseSchedulingDetailOut.getId());
                    } else {
                        recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                    }
                }

            } else if (courseType.equals(3) || courseType.equals(4) || courseType.equals(5) || courseType.equals(6)) {
                RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getSchedulingDetailId());
                if (repairCourse != null) {
                    repairCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());
                    RepairCourse repairCourseNew = new RepairCourse();
                    BeanUtils.copyProperties(repairCourse, repairCourseNew);
                    repairCourseNew.setId(idWorker.nextId());
                    repairCourseNew.setOutId(repairCourse.getId());
                    repairCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());

                    if (courseType.equals(6)) {
                        LackCourseLog lackCourseLog = iLackCourseLogService.getOneForId(repairCourse.getRecordCourseId());
                        if (lackCourseLog != null) {
                            LackCourseLog lackCourseLogOut = iLackCourseLogService.getOneForOutId(lackCourseLog.getId());
                            if (lackCourseLogOut != null) {
                                repairCourseNew.setRecordCourseId(lackCourseLogOut.getId());
                            }
                        }
                    }
                    recordCourseNew.setSchedulingDetailId(repairCourseNew.getId());
                    iRepairCourseService.save(repairCourseNew);
                    //删除原有数据
                    //repairCourse.setDeleted(2);
                    iRepairCourseService.updateById(repairCourse);
                    iRepairCourseService.updateDeleted(recordCourse.getId(), 2);
                } else {
                    recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                }
            }

            //删除原有数据
            //recordCourse.setDeleted(2);
            iRecordCourseService.updateById(recordCourse);
            iRecordCourseService.updateDeleted(recordCourse.getId(), 2);

            iRecordCourseService.save(recordCourseNew);


            QueryWrapper<RecordCost> recordCostQueryWrapper = new QueryWrapper<>();
            recordCostQueryWrapper.eq("record_course_id", recordCourse.getId());
            List<RecordCost> recordCostList = iRecordCostService.list(recordCostQueryWrapper);
            for (RecordCost recordCost : recordCostList) {
                RecordCost recordCostNew = new RecordCost();
                BeanUtils.copyProperties(recordCost, recordCostNew);
                recordCostNew.setId(idWorker.nextId());
                recordCostNew.setRecordCourseId(recordCourseNew.getId());
                iRecordCostService.save(recordCostNew);

                //删除原有数据
                //recordCost.setDeleted(2);
                iRecordCostService.updateById(recordCost);
                iRecordCostService.updateDeleted(recordCost.getId(), 2);
            }
            this.mvRecordCourseLack(recordCourse,recordCourseNew,changeSchoolDetail);
        }
        return true;
    }

    /**
     * 移动请假先扣课时，未扣钱记录
     * @param recordCourse
     * @param changeSchoolDetail
     */
    public void mvRecordCourseLack(RecordCourse recordCourse,RecordCourse recordCourseNew,ChangeSchoolDetail changeSchoolDetail){
        if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE)){
            RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCourse.getId());
            if (recordCourseLack != null){
                recordCourseLack.setChangeSchoolDetailId(changeSchoolDetail.getId());
                RecordCourseLack recordCourseLackNew = new RecordCourseLack();
                BeanUtils.copyProperties(recordCourseLack, recordCourseLackNew);

                recordCourseLackNew.setId(recordCourseNew.getId());
                recordCourseLackNew.setOutId(recordCourseLack.getId());
                iRecordCourseLackService.updateById(recordCourseLack);
                iRecordCourseLackService.save(recordCourseLackNew);
            }
        }
    }


    /**
     * 转移分班数据
     * @param changeSchoolDetail
     * @param orderDetailOld
     * @param orderDetaillNew
     * @return
     */
    public boolean mvStudentGradeData(ChangeSchoolDetail changeSchoolDetail,OrderDetail orderDetailOld,OrderDetail orderDetaillNew) throws ParseException {
        Integer lessonType =1;
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        studentGradeQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        studentGradeQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        studentGradeQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
        studentGradeQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        studentGradeQueryWrapper.eq("order_detail_id", orderDetailOld.getId());
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.ne("status", 3);
        studentGradeQueryWrapper.and(i -> i.eq("reading_status", 1).or(j -> j.gt("use_course_count", 0)));

        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        for (StudentGrade studentGrade : studentGradeList) {
            studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
            Grade gradeOld = iGradeService.getById(studentGrade.getGradeId());
            if (gradeOld == null){
                continue;
            }
            StudentGrade studentGradeNew = new StudentGrade();
            BeanUtils.copyProperties(studentGrade, studentGradeNew);
            Grade grade = iGradeService.createdForChangeSchool(studentGrade.getGradeId(), changeSchoolDetail.getInSchoolId(), gradeOld.getTeacherId(), changeSchoolDetail,true);
            /*if (grade==null){
                continue;
            }*/
            Grade gradeChangeTeacher = null;
            if (changeSchoolDetail.getChangeTeacherId() != null && changeSchoolDetail.getChangeTeacherId() != 0L) {
                gradeChangeTeacher = iGradeService.createdForChangeSchool(grade.getId(), changeSchoolDetail.getInSchoolId(), changeSchoolDetail.getChangeTeacherId(), changeSchoolDetail,false);
            }

            studentGradeNew.setId(idWorker.nextId());
            studentGradeNew.setOutId(studentGrade.getId());
            studentGradeNew.setCreatedAt(LocalDateTime.now().withNano(0));
            studentGradeNew.setSchoolId(changeSchoolDetail.getInSchoolId());

            studentGradeNew.setOrderDetailId(orderDetaillNew.getId());
            studentGradeNew.setCourseId(orderDetaillNew.getCourseId());

            studentGradeNew.setCreatedId(changeSchoolDetail.getCreatedId());
            studentGradeNew.setGradeId(grade.getId());
            if (gradeChangeTeacher != null && (studentGrade.getReadingStatus().equals(ReadingStatusEnum.IN_READING) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.STOP) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.FINISHGRADE))) {
                studentGradeNew.setReadingStatus(ReadingStatusEnum.TURN);
                studentGradeNew.setIsLast(0);
            }

            //studentGradeNew.setIsLast(studentGrade.getIsLast());
            studentGradeNew.setCreatedAt(studentGrade.getCreatedAt());
            iStudentGradeService.save(studentGradeNew);

            if (gradeChangeTeacher != null && (studentGrade.getReadingStatus().equals(ReadingStatusEnum.IN_READING) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.STOP) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.FINISHGRADE))) {
                QueryWrapper<StudentGrade> studentGradeQueryWrapperChange = new QueryWrapper<>();
                studentGradeQueryWrapperChange.eq("student_id", changeSchoolDetail.getStudentId());
                studentGradeQueryWrapperChange.eq("grade_id", gradeChangeTeacher.getId());
                studentGradeQueryWrapperChange.last("limit 1");
                StudentGrade studentGradeChange = iStudentGradeService.getOne(studentGradeQueryWrapperChange);
                //存在就不添加
                if (studentGradeChange == null) {
                    StudentGrade studentGradeChangeTeacher = new StudentGrade();
                    BeanUtils.copyProperties(studentGradeNew, studentGradeChangeTeacher);

                    studentGradeChangeTeacher.setId(idWorker.nextId());
                    studentGradeChangeTeacher.setUseCourseCount(0);
                    studentGradeChangeTeacher.setOutUseCourseCount(0);
                    studentGradeChangeTeacher.setIsLast(1);
                    studentGradeChangeTeacher.setGradeId(gradeChangeTeacher.getId());
                    studentGradeChangeTeacher.setReadingStatus(studentGrade.getReadingStatus());
                    studentGradeChangeTeacher.setCreatedAt(studentGrade.getCreatedAt());
                    iStudentGradeService.save(studentGradeChangeTeacher);
                }
                if (studentGradeChange !=null && studentGrade.getIsLast().equals(1)){
                    studentGradeChange.setCreatedAt(studentGrade.getCreatedAt());
                    iStudentGradeService.updateById(studentGradeChange);
                }
            }

            //删除原有数据
            Integer outUseCourseCount = studentGrade.getUseCourseCount() + studentGrade.getOutUseCourseCount();
            Integer userCourseCount = 0;
            studentGrade.setOutUseCourseCount(outUseCourseCount);//累计转出课次
            studentGrade.setUseCourseCount(userCourseCount);

            //studentGrade.setDeleted(2);
            studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
            //studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));
            iStudentGradeService.updateById(studentGrade);
            iStudentGradeService.updateDeleted(studentGrade.getId(), 2);
        }
        return true;
    }


    /**
     * 转移记上课数据
     * @param changeSchoolDetail
     * @param orderDetailOld
     * @param orderDetaillNew
     * @return
     */
    public boolean mvRecordCourse(ChangeSchoolDetail changeSchoolDetail,OrderDetail orderDetailOld,OrderDetail orderDetaillNew){
        Organization inSchoolInfo = iOrganizationService.getById(changeSchoolDetail.getInSchoolId());
        Integer lessonType =1;
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        recordCourseQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        recordCourseQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        recordCourseQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        recordCourseQueryWrapper.eq("quarter", changeSchoolDetail.getQuarterNum());
        recordCourseQueryWrapper.eq("lesson_type", lessonType);
        recordCourseQueryWrapper.orderByAsc("id");
        List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
        for (RecordCourse recordCourse : recordCourseList) {
            recordCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());

            RecordCourse recordCourseNew = new RecordCourse();
            BeanUtils.copyProperties(recordCourse, recordCourseNew);

            recordCourseNew.setId(idWorker.nextId());
            recordCourseNew.setOutId(recordCourse.getId());
            recordCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            recordCourseNew.setSchoolName(inSchoolInfo.getName());
            recordCourseNew.setCreatedAt(LocalDateTime.now().withNano(0));

            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("out_id",recordCourseNew.getOrderDetailId());
            orderDetailQueryWrapper.last("limit 1");
            OrderDetail orderDetail = iOrderDetailService.getOne(orderDetailQueryWrapper);
            if (orderDetail!= null){
                recordCourseNew.setOrderDetailId(orderDetail.getId());
            }

            Integer courseType = recordCourse.getCourseType();

            //课程类别：1精品课（正常排课），3补课，4调课，5消课,6缺课补课
            if (courseType.equals(1)) {
                CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOneForId(recordCourse.getSchedulingDetailId());
                if (courseSchedulingDetail != null) {
                    CourseSchedulingDetail courseSchedulingDetailOut = iCourseSchedulingDetailService.getOneForOutId(courseSchedulingDetail.getId());
                    if (courseSchedulingDetailOut != null) {
                        recordCourseNew.setSchedulingDetailId(courseSchedulingDetailOut.getId());
                    } else {
                        recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                    }
                }

            } else if (courseType.equals(3) || courseType.equals(4) || courseType.equals(5) || courseType.equals(6)) {
                RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getSchedulingDetailId());
                if (repairCourse != null) {
                    repairCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());
                    RepairCourse repairCourseNew = new RepairCourse();
                    BeanUtils.copyProperties(repairCourse, repairCourseNew);
                    repairCourseNew.setId(idWorker.nextId());
                    repairCourseNew.setOutId(repairCourse.getId());
                    repairCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());

                    if (courseType.equals(6)) {
                        LackCourseLog lackCourseLog = iLackCourseLogService.getOneForId(repairCourse.getRecordCourseId());
                        if (lackCourseLog != null) {
                            LackCourseLog lackCourseLogOut = iLackCourseLogService.getOneForOutId(lackCourseLog.getId());
                            if (lackCourseLogOut != null) {
                                repairCourseNew.setRecordCourseId(lackCourseLogOut.getId());
                            }
                        }
                    }
                    recordCourseNew.setSchedulingDetailId(repairCourseNew.getId());
                    iRepairCourseService.save(repairCourseNew);
                    //删除原有数据
                    //repairCourse.setDeleted(2);
                    iRepairCourseService.updateById(repairCourse);
                    iRepairCourseService.updateDeleted(recordCourse.getId(), 2);
                } else {
                    recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                }
            }

            //删除原有数据
            //recordCourse.setDeleted(2);
            iRecordCourseService.updateById(recordCourse);
            iRecordCourseService.updateDeleted(recordCourse.getId(), 2);

            iRecordCourseService.save(recordCourseNew);


            QueryWrapper<RecordCost> recordCostQueryWrapper = new QueryWrapper<>();
            recordCostQueryWrapper.eq("record_course_id", recordCourse.getId());
            List<RecordCost> recordCostList = iRecordCostService.list(recordCostQueryWrapper);
            for (RecordCost recordCost : recordCostList) {
                RecordCost recordCostNew = new RecordCost();
                BeanUtils.copyProperties(recordCost, recordCostNew);
                recordCostNew.setId(idWorker.nextId());
                recordCostNew.setRecordCourseId(recordCourseNew.getId());
                iRecordCostService.save(recordCostNew);

                //删除原有数据
                //recordCost.setDeleted(2);
                iRecordCostService.updateById(recordCost);
                iRecordCostService.updateDeleted(recordCost.getId(), 2);
            }
            this.mvRecordCourseLack(recordCourse,recordCourseNew,changeSchoolDetail);
        }
        return true;
    }

    /**
     * 获取转入校区的价格数据
     *
     * @return
     */
    public CoursePricing getCoursePricing(Course course, Integer outHouse, Long inSchoolId) {
        QueryWrapper<CoursePricing> coursePricingQueryWrapper = new QueryWrapper<>();
        if (course.getOpeningSchoolType().getKey().equals(1)) {
            //select id from course_price_school where course_id = and school_id =
            coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =0 and deleted=0");
        } else {
            coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =" + inSchoolId + " and deleted=0");
        }

        if ((outHouse % 45) == 0) {
            coursePricingQueryWrapper.eq("count", 45);
        } else {
            coursePricingQueryWrapper.eq("count", 3);
        }
        //coursePricingQueryWrapper.eq("status",1);
        coursePricingQueryWrapper.last("limit 1");

        CoursePricing coursePricing = iCoursePricingService.getOne(coursePricingQueryWrapper);

        return coursePricing;
    }


    /**
     * 修改转校分班与记上课数据(全部转出)
     *
     * @param resChangeSchoolReurn
     * @return
     */
    @Override
    public boolean updateChangeSchoolData(ChangeSchoolDetail changeSchoolDetail, ResChangeSchoolReturn resChangeSchoolReurn) throws ParseException {

        Organization inSchoolInfo = iOrganizationService.getById(changeSchoolDetail.getInSchoolId());

        //新报名订单id
        OrderDetail orderDetail = resChangeSchoolReurn.getOrderDetail();
        Course course = resChangeSchoolReurn.getCourse();

        Integer lessonType = 1;

        /**
         * 找出分班信息
         */
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        studentGradeQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        studentGradeQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        studentGradeQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
        studentGradeQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        studentGradeQueryWrapper.eq("lesson_type", lessonType);
        studentGradeQueryWrapper.ne("status", 3);
        studentGradeQueryWrapper.and(i -> i.eq("reading_status", 1).or(j -> j.gt("use_course_count", 0)));

        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        for (StudentGrade studentGrade : studentGradeList) {
            studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
            Grade gradeOld = iGradeService.getById(studentGrade.getGradeId());
            if (gradeOld == null){
                continue;
            }
            StudentGrade studentGradeNew = new StudentGrade();
            BeanUtils.copyProperties(studentGrade, studentGradeNew);
            Grade grade = iGradeService.createdForChangeSchool(studentGrade.getGradeId(), changeSchoolDetail.getInSchoolId(), gradeOld.getTeacherId(), changeSchoolDetail,true);
            /*if (grade==null){
                continue;
            }*/

            Grade gradeChangeTeacher = null;
            if (changeSchoolDetail.getChangeTeacherId() != null && changeSchoolDetail.getChangeTeacherId() != 0L) {
                gradeChangeTeacher = iGradeService.createdForChangeSchool(grade.getId(), changeSchoolDetail.getInSchoolId(), changeSchoolDetail.getChangeTeacherId(), changeSchoolDetail,false);
            }

            studentGradeNew.setId(idWorker.nextId());
            studentGradeNew.setOutId(studentGrade.getId());
            //studentGradeNew.setCreatedAt(LocalDateTime.now().withNano(0));
            studentGradeNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            studentGradeNew.setOrderDetailId(orderDetail.getId());
            studentGradeNew.setCourseId(course.getId());
            studentGradeNew.setCreatedId(changeSchoolDetail.getCreatedId());

            studentGradeNew.setGradeId(grade.getId());


            if (gradeChangeTeacher != null && (studentGrade.getReadingStatus().equals(ReadingStatusEnum.IN_READING) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.STOP))) {
                studentGradeNew.setReadingStatus(ReadingStatusEnum.TURN);
            }

            //studentGradeNew.setIsLast(studentGrade.getIsLast());
            iStudentGradeService.save(studentGradeNew);

            if (gradeChangeTeacher != null && (studentGrade.getReadingStatus().equals(ReadingStatusEnum.IN_READING) || studentGrade.getReadingStatus().equals(ReadingStatusEnum.STOP))) {
                QueryWrapper<StudentGrade> studentGradeQueryWrapperChange = new QueryWrapper<>();
                studentGradeQueryWrapperChange.eq("student_id", changeSchoolDetail.getStudentId());
                studentGradeQueryWrapperChange.eq("grade_id", gradeChangeTeacher.getId());
                Long count = iStudentGradeService.count(studentGradeQueryWrapperChange);
                //存在就不添加
                if (count.equals(0L)) {
                    StudentGrade studentGradeChangeTeacher = new StudentGrade();
                    BeanUtils.copyProperties(studentGradeNew, studentGradeChangeTeacher);

                    studentGradeChangeTeacher.setId(idWorker.nextId());
                    studentGradeChangeTeacher.setUseCourseCount(0);
                    studentGradeChangeTeacher.setOutUseCourseCount(0);
                    studentGradeChangeTeacher.setIsLast(1);
                    studentGradeChangeTeacher.setGradeId(gradeChangeTeacher.getId());
                    studentGradeChangeTeacher.setReadingStatus(ReadingStatusEnum.IN_READING);
                    iStudentGradeService.save(studentGradeChangeTeacher);
                }
            }

            //删除原有数据
            Integer outUseCourseCount = studentGrade.getUseCourseCount() + studentGrade.getOutUseCourseCount();
            Integer userCourseCount = 0;
            studentGrade.setOutUseCourseCount(outUseCourseCount);//累计转出课次
            studentGrade.setUseCourseCount(userCourseCount);

            //studentGrade.setDeleted(2);
            studentGrade.setChangeSchoolDetailId(changeSchoolDetail.getId());
            //studentGrade.setCreatedAt(LocalDateTime.now().withNano(0));
            iStudentGradeService.updateById(studentGrade);
            iStudentGradeService.updateDeleted(studentGrade.getId(), 2);
        }

        QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();
        lackCourseLogQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        lackCourseLogQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        lackCourseLogQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        lackCourseLogQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        lackCourseLogQueryWrapper.eq("quarter_num", changeSchoolDetail.getQuarterNum());
        lackCourseLogQueryWrapper.eq("lesson_type", lessonType);

        List<LackCourseLog> lackCourseLogList = iLackCourseLogService.list(lackCourseLogQueryWrapper);
        for (LackCourseLog lackCourseLog : lackCourseLogList) {
            lackCourseLog.setChangeSchoolDetailId(changeSchoolDetail.getId());

            LackCourseLog lackCourseLogNew = new LackCourseLog();
            BeanUtils.copyProperties(lackCourseLog, lackCourseLogNew);
            lackCourseLogNew.setId(idWorker.nextId());
            lackCourseLogNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            lackCourseLogNew.setOutId(lackCourseLog.getId());
            iLackCourseLogService.save(lackCourseLogNew);

            //删除原有数据
            //lackCourseLog.setDeleted(2);
            iLackCourseLogService.updateById(lackCourseLog);
            iLackCourseLogService.updateDeleted(lackCourseLog.getId(), 2);
        }

        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id", changeSchoolDetail.getOutSchoolId());
        recordCourseQueryWrapper.eq("subjects_id", changeSchoolDetail.getSubjectsId());
        recordCourseQueryWrapper.eq("student_id", changeSchoolDetail.getStudentId());
        recordCourseQueryWrapper.eq("year_part", changeSchoolDetail.getYearPart());
        recordCourseQueryWrapper.eq("quarter", changeSchoolDetail.getQuarterNum());
        recordCourseQueryWrapper.eq("lesson_type", lessonType);
        recordCourseQueryWrapper.orderByAsc("id");
        List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
        for (RecordCourse recordCourse : recordCourseList) {
            recordCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());

            RecordCourse recordCourseNew = new RecordCourse();
            BeanUtils.copyProperties(recordCourse, recordCourseNew);

            recordCourseNew.setId(idWorker.nextId());
            recordCourseNew.setOutId(recordCourse.getId());
            recordCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());
            recordCourseNew.setSchoolName(inSchoolInfo.getName());
            recordCourseNew.setOutId(recordCourse.getId());
            recordCourseNew.setCreatedAt(LocalDateTime.now().withNano(0));

            Integer courseType = recordCourse.getCourseType();

            //课程类别：1精品课（正常排课），3补课，4调课，5消课,6缺课补课
            if (courseType.equals(1)) {
                CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOneForId(recordCourse.getSchedulingDetailId());
                if (courseSchedulingDetail != null) {
                    CourseSchedulingDetail courseSchedulingDetailOut = iCourseSchedulingDetailService.getOneForOutId(courseSchedulingDetail.getId());
                    if (courseSchedulingDetailOut != null) {
                        recordCourseNew.setSchedulingDetailId(courseSchedulingDetailOut.getId());
                    } else {
                        recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                    }
                }

            } else if (courseType.equals(3) || courseType.equals(4) || courseType.equals(5) || courseType.equals(6)) {
                RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getSchedulingDetailId());
                if (repairCourse != null) {
                    repairCourse.setChangeSchoolDetailId(changeSchoolDetail.getId());
                    RepairCourse repairCourseNew = new RepairCourse();
                    BeanUtils.copyProperties(repairCourse, repairCourseNew);
                    repairCourseNew.setId(idWorker.nextId());
                    repairCourseNew.setOutId(repairCourse.getId());
                    repairCourseNew.setSchoolId(changeSchoolDetail.getInSchoolId());

                    if (courseType.equals(6)) {
                        LackCourseLog lackCourseLog = iLackCourseLogService.getOneForId(repairCourse.getRecordCourseId());
                        if (lackCourseLog != null) {
                            LackCourseLog lackCourseLogOut = iLackCourseLogService.getOneForOutId(lackCourseLog.getId());
                            if (lackCourseLogOut != null) {
                                repairCourseNew.setRecordCourseId(lackCourseLogOut.getId());
                            }
                        }
                    }
                    recordCourseNew.setSchedulingDetailId(repairCourseNew.getId());
                    iRepairCourseService.save(repairCourseNew);
                    //删除原有数据
                    //repairCourse.setDeleted(2);
                    iRepairCourseService.updateById(repairCourse);
                    iRepairCourseService.updateDeleted(recordCourse.getId(), 2);
                } else {
                    recordCourseNew.setSchedulingDetailId(idWorker.nextId());
                }
            }

            //删除原有数据
            //recordCourse.setDeleted(2);
            iRecordCourseService.updateById(recordCourse);
            iRecordCourseService.updateDeleted(recordCourse.getId(), 2);

            iRecordCourseService.save(recordCourseNew);


            QueryWrapper<RecordCost> recordCostQueryWrapper = new QueryWrapper<>();
            recordCostQueryWrapper.eq("record_course_id", recordCourse.getId());
            List<RecordCost> recordCostList = iRecordCostService.list(recordCostQueryWrapper);
            for (RecordCost recordCost : recordCostList) {
                RecordCost recordCostNew = new RecordCost();
                BeanUtils.copyProperties(recordCost, recordCostNew);
                recordCostNew.setId(idWorker.nextId());
                recordCostNew.setRecordCourseId(recordCourseNew.getId());
                iRecordCostService.save(recordCostNew);

                //删除原有数据
                //recordCost.setDeleted(2);
                iRecordCostService.updateById(recordCost);
                iRecordCostService.updateDeleted(recordCost.getId(), 2);
            }
        }
        return true;
    }


    /**
     * 转智能课，和刷题班
     * @param
     * @return
     */
    @Override
    public boolean mvOtherCourseDataForTeacher(ChangeSchoolDetail changeSchoolDetailParam) throws ParseException {
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

        Organization inSchool = iOrganizationService.getById(changeSchoolDetailParam.getInSchoolId());

        QueryWrapper<OrderApply> orderApplyQueryWrapper = new QueryWrapper<>();
        orderApplyQueryWrapper.eq("year_part", changeSchoolDetailParam.getYearPart());
        orderApplyQueryWrapper.eq("quarter_num", changeSchoolDetailParam.getQuarterNum());
        orderApplyQueryWrapper.eq("school_id", changeSchoolDetailParam.getOutSchoolId());
        orderApplyQueryWrapper.eq("student_id", changeSchoolDetailParam.getStudentId());
        Integer lessonType = 2;
        if (changeSchoolDetailParam.getSubjectsId().equals(1L)){
            lessonType = 2;
        }else {
            lessonType = 3;
        }

        orderApplyQueryWrapper.in("lesson_type", lessonType);

        orderApplyQueryWrapper.ne("status", 3);
        List<OrderApply> orderApplyList = iOrderApplyService.list(orderApplyQueryWrapper);
        for (OrderApply orderApply : orderApplyList) {
            Long orderId = orderApply.getId();
            //orderApply.setId(idWorker.nextId());
            orderApply.setOutId(orderId);
            orderApply.setSchoolId(changeSchoolDetailParam.getInSchoolId());
            orderApply.setChangeSchoolDetailId(changeSchoolDetailParam.getId());
            orderApply.setHandleSchoolId(inSchool.getId());
            orderApply.setHandleSchoolName(inSchool.getName());

            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("order_id", orderId);
            orderDetailQueryWrapper.eq("subjects_id", changeSchoolDetailParam.getSubjectsId());
            List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);

            for (OrderDetail orderDetail : orderDetailList) {
                orderDetail.setSchoolId(changeSchoolDetailParam.getInSchoolId());
                orderDetail.setOutId(orderDetail.getId());
                orderDetail.setChangeSchoolDetailId(changeSchoolDetailParam.getId());
                orderDetail.setCreatedAt(dateTimeNow);
                iOrderDetailService.updateById(orderDetail);
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("student_id",changeSchoolDetailParam.getStudentId());
                studentGradeQueryWrapper.eq("order_detail_id",orderDetail.getId());
                List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade:studentGradeList){
                    Grade gradeOld = iGradeService.getById(studentGrade.getGradeId());
                    StudentGrade studentGradeNew = new StudentGrade();
                    BeanUtils.copyProperties(studentGrade, studentGradeNew);
                    QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
                    gradeQueryWrapper.eq("year_part", changeSchoolDetailParam.getYearPart());
                    gradeQueryWrapper.eq("quarter_num", changeSchoolDetailParam.getQuarterNum());
                    gradeQueryWrapper.eq("subjects_id", changeSchoolDetailParam.getSubjectsId());
                    gradeQueryWrapper.eq("school_id", inSchool.getId());
                    gradeQueryWrapper.eq("lesson_type", lessonType);
                    gradeQueryWrapper.eq("status",1);
                    gradeQueryWrapper.eq("week_dates",gradeOld.getWeekDates());
                    gradeQueryWrapper.last("limit 1");
                    Grade grade = null;
                    Grade gradeInSchool = iGradeService.getOne(gradeQueryWrapper);
                    if (gradeInSchool!=null){
                        grade = gradeInSchool;
                    }else {
                        grade = iGradeService.createdForChangeSchool(studentGrade.getGradeId(), changeSchoolDetailParam.getInSchoolId(), gradeOld.getTeacherId(), changeSchoolDetailParam,false);
                    }
                    if (grade!=null){
                        studentGrade.setGradeId(grade.getId());
                    }
                    studentGrade.setChangeSchoolDetailId(changeSchoolDetailParam.getId());
                    studentGrade.setSchoolId(inSchool.getId());
                    iStudentGradeService.updateById(studentGrade);
                }
            }

            if (orderDetailList.size()>0){
                iOrderApplyService.updateById(orderApply);
            }

        }
        return true;
    }

    /**
     * 转移智能课与刷题班记上课与签到数据
     * @param changeSchoolDetailParam
     */
    public void mvOtherCourseData(ChangeSchoolDetail changeSchoolDetailParam){
        Organization inSchool = iOrganizationService.getById(changeSchoolDetailParam.getInSchoolId());
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("year_part",changeSchoolDetailParam.getYearPart());
        recordCourseQueryWrapper.eq("quarter",changeSchoolDetailParam.getQuarterNum());
        recordCourseQueryWrapper.eq("student_id",changeSchoolDetailParam.getStudentId());
        recordCourseQueryWrapper.in("lesson_type",2,3);
        List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
        for (RecordCourse recordCourse:recordCourseList){
            recordCourse.setSchoolId(inSchool.getId());
            recordCourse.setSchoolName(inSchool.getName());
            iRecordCourseService.updateById(recordCourse);
        }

        Quarter quarterNow = iQuarterService.getQuarterForYearAndNum(changeSchoolDetailParam.getYearPart(),changeSchoolDetailParam.getQuarterNum());
        QueryWrapper<StudentSignIn> studentSignInQueryWrapper = new QueryWrapper<>();
        studentSignInQueryWrapper.eq("school_id", changeSchoolDetailParam.getOutSchoolId());
        studentSignInQueryWrapper.eq("subjects_id", changeSchoolDetailParam.getSubjectsId());
        studentSignInQueryWrapper.eq("student_id", changeSchoolDetailParam.getStudentId());
        studentSignInQueryWrapper.in("lesson_type", 2,3);
        studentSignInQueryWrapper.ge("add_date", quarterNow.getStartDate());
        studentSignInQueryWrapper.orderByAsc("id");
        List<StudentSignIn> studentSignInList =iStudentSignInService.list(studentSignInQueryWrapper);
        for (StudentSignIn studentSignIn:studentSignInList){
            CourseSchedulingDetail courseSchedulingDetail = null;
            if (studentSignIn.getSchedulingDetailId() !=null){
                courseSchedulingDetail = iCourseSchedulingDetailService.getOneForId(studentSignIn.getSchedulingDetailId());

            }
            if (courseSchedulingDetail != null) {
                CourseSchedulingDetail courseSchedulingDetailOut = iCourseSchedulingDetailService.getOneForOutId(courseSchedulingDetail.getId());
                if (courseSchedulingDetailOut != null) {
                    studentSignIn.setSchedulingDetailId(courseSchedulingDetailOut.getId());
                } else {
                    studentSignIn.setSchedulingDetailId(idWorker.nextId());
                }
            }
        }
    }
}
